NodeJS, passport-jwt: Authenticate all user except in list

user1790300 Source

I am setting up a nodejs project with passportjs and passport-jwt. I see where you can specify passport.authenticate for each route you want to secure. However, I do not see a way to lock down all router except maybe login and register. I see where express-jwt allows for the use of express-unless, which seems to accomplish this functionality. Is there a similar mechanism for passport-jwt and if so how would this be accomplished?

node.jspassport.js

Answers

answered 1 year ago Boris #1

Actually you don't even need express-unless you can use the fact that express allow to register middlewares that get executed all the time to do your filtering

const express = require('express');
const app = express(); 

function authenticateSomeRoutesMiddleware(req, res, next) {
    if (/(login|register)/.test(req.originalUrl)) {
        // No authentication needed
        return next();
    } else {
        // Option 1 => use default passport logic 
        // which respond with a 401 unauthorized status if authentication fails
        passport.authenticate('jwt', { session: false}), function(req, res, next) {
            // Do something now you know that the user has been authenticated
            return next(); // this will call the next middleware on the stack 
        })(req, res, next);

        // Option 2: use a custom callback to allow your application 
        // to handle success or failure
        // As per passport spec: 
        // - 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.

        passport.authenticate('local', function(err, user, info) {
            if (err) {
                // Error in authentication process; handle it or call...
                return next(err);
            }
            if (!user) {
                // Authentication failed (based on your strategy's implementation)
                // You can for example try again
                return res.redirect('/login');
            }

            // If you are using session to store the user call req.logIn() else call `return next()` directly
            req.logIn(user, function(err) {
                if (err) { return next(err); }
                return next();
            });
        })(req, res, next);
    }
}


// add this BEFORE your route definitions
app.use(authenticateSomeRoutesMiddleware);

// add all your routes here
app.use('/login', function(req, res, next) {
    // do something
});
app.use('/register', function(req, res, next) {
    // do something else
});
app.use('/some/protected/route', function(req, res, next) {
    // this will get called once the authentication process has been cleared
});
//...

comments powered by Disqus