Search code examples
node.jsauthenticationexpresspassport.jsjwt

Use Passport Local & JWT Strategy on same app (on same route)


so my route (for '/dash') looks like this:

// validating using JWT
router.post('/dash', passport.authenticate('jwt', {session: false}), function (req, res) {
    res.json({'success': true});
});

// validating using LOCAL
router.post('/dash', authenticationHelpers.isAuth, function (req, res) {
    res.json({'success': true});
});

// authenticationHelpers.isAuth
function isAuth(req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.status(401).json({"authenticated": false});
}

So, how do I use both Local & JWT Strategy on same app (on same route) ? How do I combine them both.

Note: Local for web app, JWT for mobile app


Solution

  • Finally figured it out.

    Modified isAuth function:

    function isAuth(req, res, next) {
        if (req.headers.authorization) {
            passport.authenticate('jwt', {session: false}, function (err, user, info) {
                if ((!err || !info) && user) {
                    req.user = user;
                    return next();
                }
                res.status(401).json({authenticated: false, message: "Login expired."});
            })(req, res, next);
        } else {
            if (req.isAuthenticated())
                return next();
            res.status(401).json({authenticated: false});
        }
    }
    

    Suggestions are welcomed...