NodeJS,passport-jwt:验证除列表外的所有用户

时间:2017-05-16 15:39:48

标签: node.js passport.js

我正在使用passportjs和passport-jwt建立一个nodejs项目。我知道你可以为你想要保护的每条路线指定passport.authenticate。但是,除了登录和注册之外,我没有看到锁定所有路由器的方法。我看到express-jwt允许使用express-unless,这似乎完成了这个功能。对于passport-jwt是否有类似的机制,如果是这样,将如何实现?

1 个答案:

答案 0 :(得分:0)

实际上你甚至不需要express-unless你可以使用表达允许注册中间件的事实,这些中间件一直被执行来进行过滤

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
});
//...