本文介绍了Passport.js重定向到| successRedirect:'/profile'|但是req.isAuthenticated()返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码是由Node.js + Express + Passport.js开发的应用程序的一部分.有效用户将被重定向到/profile
url(successRedirect),但是req.isAuthenticated
返回false,并且req.user
也是undefined
.我不知道可能是什么原因:
The following code is a section of an app developed by Node.js + Express + Passport.js. A valid user gets redirected to /profile
url (successRedirect), however the req.isAuthenticated
returns false and also the req.user
is undefined
. I couldn't figure out what might be the cause:
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
});
})
推荐答案
在需要进行身份验证的每条路由上,您都应该申请通行证.对中间件进行身份验证,即:
On each route where authentication is needed you should apply passport.authenticate middleware i.e :
app.get('/profile', passport.authenticate('local'), (req, res) => {
console.log(req.user);
console.log(req.isAuthenticated());
}
请参见护照文档
这篇关于Passport.js重定向到| successRedirect:'/profile'|但是req.isAuthenticated()返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!