2017-05-16 20 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 
}); 
//...