Search code examples
node.jsjwtpassport-jwt

How to perform some logic if JWT token is not present in header?


I am using passport-jwt and there is an endpoint, which should return some data from database if jwt token is not present in header. Is it possible to apply some logic instead of just sending Unauthorized 401?

router.get(
    '/get/items',
    passport.authenticate('jwt', {session: false}),
    (req, res) => {
     // reaches this point only after validating token
     ...
    }
);

So if jwt token is present, based on it endpoint should return some data. If not, some other data from db should be returned


Solution

  • I think the custom callback is an option. It is passed as last parameter to authenticate(strategy, options, callback) method and it will allow you to set the behavior that you wish.

    Your code will look like:

    app.get('/get/items', (req, res, next) => {
    
        passport.authenticate('jwt', { session: false }, (err, user, info) => {
            if (!user) {
                /* 
                    Unauthorized accees.
                    Handle here the request as u wish
                */
    
                /* Do some custom logic and return your desired result */
                return res.status(401).json({ success: false, message: 'Unauthorized access!' });
            }
    
            /* User is authorized. Do other stuff here and return your desired result*/
            return res.status(200).json({ success: true, message: 'Congratulations!' });
        })(req, res, next);
        
    });
    

    In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.

    If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional info argument will be passed, containing additional details provided by the strategy's verify callback.

    The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.

    Source