CaptRisky CaptRisky - 15 days ago 11
Node.js Question

Is node passport custom callback as middleware possible for express routes?

I'm creating a simple Rest Api with node.js and I'm securing it with jwt tokens, I have set up passport and passport-jwt to authenticate which works fine and if there is an error with the jwt token or its non existent, passport will send a 401 and body text of 'Unauthorized'. I know how to change the error for a route to send back a custom error message which I want by doing the following;

router.route('/test')
.put(function(req, res, next) {
passport.authenticate('jwt', { session: false }, function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.send("Custom Unauthorised").end(); }
return res.send("Test Route Accessed").end();
})(req, res, next);
});


I have around 20 routes and I name them similar to the following;

router.route('/books/:id/authors').get(passport.authenticate('jwt', { session: false }), myRoutes.books.authors);


Now you will notice that I store resource specific routes in their own files (i.e myRoutes.books) so my question is, is there a way to have the custom callbacks as middleware that wont require a major restructure of the route files?

Cheers

Answer

I hope I understood correctly your question.

Create a function let's call it jwt

function jwt (req, res, next){
    passport.authenticate('jwt', { session: false }, function(err, user, info) { 
        if (err) { return next(err); } 
        if (!user) { return res.send("Custom Unauthorised").end(); } 
        // edit as per comment
        //return res.send("Test Route Accessed").end();
        req.user = user;   // Forward user information to the next middleware
        next();
    })(req, res, next);
}

And use it as middleware

router.get('/bla', jwt, handleBla);
Comments