2017-05-16 22 views
0

我使用passportjs和passport-jwt设置了一个nodejs项目。我看到你可以指定passport.authenticate你想要保护的每条路线。但是,我没有看到锁定所有路由器的方式,除了可能的登录和注册。我看到了express-jwt允许使用express的地方 - 除非这似乎完成了这个功能。对于passport-jwt是否有类似的机制,如果有的话,这将如何完成?NodeJS,passport-jwt:验证除列表中的所有用户

回答

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