Passport.js 重定向到 |successRedirect: '/profile'|但是 req.isAuthenticated() returns 错误
Passport.js redirects to |successRedirect: '/profile'| but req.isAuthenticated() returns false
以下代码是Node.js + Express + Passport.js开发的一个app的一部分。一个有效的用户被重定向到 /profile
url(成功重定向),但是 req.isAuthenticated
returns false 并且 req.user
是 undefined
。我无法弄清楚可能是什么原因:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/profile',// <-- a valid user gets redirected to `/profile`
failureRedirect: '/',
failureFlash: true
})
);
app.get('/profile',function(req,res){
console.log('req.user: \n'+req.user)
console.log('req.isAuthenticated(): '+req.isAuthenticated()) // <-- However, the `req.isAuthenticated()` returns false
console.log('req.isAuthenticated: '+req.isAuthenticated)
res.render('profile.ejs',{
/*username: req.user.username*/ // <-- req.user is undefined
});
})
在需要身份验证的每个路由上,您应该应用 passport.authenticate 中间件,即:
app.get('/profile', passport.authenticate('local'), (req, res) => {
console.log(req.user);
console.log(req.isAuthenticated());
}
以下代码是Node.js + Express + Passport.js开发的一个app的一部分。一个有效的用户被重定向到 /profile
url(成功重定向),但是 req.isAuthenticated
returns false 并且 req.user
是 undefined
。我无法弄清楚可能是什么原因:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/profile',// <-- a valid user gets redirected to `/profile`
failureRedirect: '/',
failureFlash: true
})
);
app.get('/profile',function(req,res){
console.log('req.user: \n'+req.user)
console.log('req.isAuthenticated(): '+req.isAuthenticated()) // <-- However, the `req.isAuthenticated()` returns false
console.log('req.isAuthenticated: '+req.isAuthenticated)
res.render('profile.ejs',{
/*username: req.user.username*/ // <-- req.user is undefined
});
})
在需要身份验证的每个路由上,您应该应用 passport.authenticate 中间件,即:
app.get('/profile', passport.authenticate('local'), (req, res) => {
console.log(req.user);
console.log(req.isAuthenticated());
}