使用Passport.js更正身份validation模式
看来护照文件build议使用如下模式:
app.get("/my/protected/resource", passport.authenticate("local"), function(req, res){ res.json({my:"protected resource"}); });
作为authentication后保护资源的标准方式。 然而,正如我一再尝试这个策略,它一再给我401 - Unauthorized
。 相反,如下所示的中间件解决scheme的工作:
exports.loggedIn = function(req, res, next) { console.log('Checking credentials...'); if(req.isAuthenticated()){ next(); } else { res.redirect("/"); } };
但是,这个要么没有find,要么在文档中不突出。 哪两个是使用passport.js保护资源的标准和正确方法?
如果您使用会话,我通常使用这种types的模式:
app.get('/resource', passport.authenticate('local', { successRedirect: '/success', failureRedirect: '/login', failureFlash: 'Invalid username or password' }))
如图所示http://passportjs.org/guide/authenticate/
如果你想在相同的function的响应:
app.get('/resource', passport.authenticate('local', { failureRedirect: '/login', failureFlash: 'Invalid username or password' }), function(req, res){ res.json({my:"protected resource"}); })
如果你想被redirect到“/”(就像你的第二个例子那样),而不是在尝试访问未经validation的受保护资源时使用passport.authenticate
获得401(默认行为),那么可以使用指定的redirect选项在您链接的文档页面的第二部分:
app.get("/my/protected/resource", passport.authenticate("local", {failureRedirect: '/' }), function(req, res){ res.json({my:"protected resource"}); });