0

i am new to developing apis in node js. recently i started working on a node js application there i use jwt tokens to authentication purposes.

my jwt validation function is as bellow

var jwt = require('jsonwebtoken');
var config = require('../config.js')

var JwtValidations = {


    //will validate the JTW token
    JwtValidation: function(req, res, next, callback) {

        // check header or url parameters or post parameters for token
        var token = req.body.token || req.query.token || req.headers['x-access-token'];

        // decode token
        if (token) {
            // verifies secret and checks exp
            jwt.verify(token, config.secret, callback);

        } else {
            // if there is no token
            // return an error
            return res.status(403).send({
                success: false,
                message: 'No token provided.'
            });

        }



    }


}
module.exports = JwtValidations;

to this function i am passing a call back function so that if the jtw token validation passed i can serve to the request. bellow is one example of adding a user to the system

// addmin a user to the database
router.post('/add', function(req, res, next) {

    JwtValidations.JwtValidation(req, res, next, function(err, decoded) {
        if (err) {
            return res.json({ success: false, message: 'Failed to authenticate token.' });
        } else {
            retrunval = User.addUser(req.body);
            if (retrunval === true) {
                res.json({ message: "_successful", body: true });
            } else {
                res.json({ message: "_successful", body: false });
            }
        }
    })

});

// addmin a user to the database
router.put('/edit', function(req, res, next) {
    JwtValidations.JwtValidation(req, res, next, function(err, decoded) {
        if (err) {
            return res.json({ success: false, message: 'Failed to authenticate token.' });
        } else {
            User.UpdateUser(req.body, function(err, rows) {
                if (err) {
                    res.json({ message: "_err", body: err });
                } else {
                    res.json({ message: "_successful", body: rows });
                }
            });
        }
    })
});

as you can see in both of these function i am repeating same code segment

return res.json({ success: false, message: 'Failed to authenticate token.' });

how do i avoid that and call the callback function if and only if JwtValidations.JwtValidation does not consists any error

2 Answers 2

2

how do i avoid that and call the callback function if and only if JwtValidations.JwtValidation does not consists any error

Just handle it at a level above the callback, either in JwtValidations.JwtValidation itself or a wrapper you put around the callback.

If you were doing it in JwtValidations.JwtValidation itself, you'd do this where you call the callback:

if (token) {
    // verifies secret and checks exp
    jwt.verify(token, config.secret, function(err, decoded) {
        if (err) {
            return res.json({ success: false, message: 'Failed to authenticate token.' });
        }
        callback(decoded);
    });
} else /* ... */

Now when you use it, you know either you'll get the callback with a successfully-decoded token, or you won't get a callback at all but an error response will have been sent for you:

router.put('/edit', function(req, res, next) {
    JwtValidations.JwtValidation(req, res, next, function(decoded) {
        User.UpdateUser(req.body, function(err, rows) {
            if (err) {
                res.json({ message: "_err", body: err });
            } else {
                res.json({ message: "_successful", body: rows });
            }
        });
    })
});

The code above is using a lot of (old-style) NodeJS callbacks. That's absolutely fine, but you may find it's simpler to compose bits of code if you use promises instead. One of the useful things do is split the return path in two, one for normal resolution, one for errors (rejection).

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you this worked. Also if you can tell me if this is the right way of doing this that would be great.
@pavithrarox: I can't speak to the JWT authentication part specifically. I'd agree with Daniel Netzer's answer about using it as middleware rather than in each route endpoint, though.
Thank you so much. i will look in to that also.
1

Use the jwt authentication function as a middleware function and not as a route, plenty of examples on the express documentation. http://expressjs.com/en/guide/using-middleware.html

1 Comment

by the way making it a MW function allows you to add this specific function on plenty more routes if you want to validate the JWT on every request, which is usually what happens on servers with authentication of all sorts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.