我使用nodejs和expressjs以及passportjs进行身份验证。我在会话中创建了登录并保存了用户ID,但是当检查经过身份验证的用户的req.isAuthenticated()方法时,它总是返回false。我试图找到该方法的文档,但没有取得任何成功。]
以下是来自routes.js的索引和登录逻辑
router.get('/', ensureAuthenticated, function(req, res, next) {
res.render('index', { 'message': req.flash('success_msg') });
});
router.get('/login', (req, res)=>{
res.render('auth/login', { 'message': req.flash('fail_msg') });
});
router.post('/login',
(req, res, next) => {
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
})(req, res, next);
});
passport.use(new LocalStrategy({
passReqToCallback: true // don't forget this
},(req, username, password, done)=>{
User.findOne({username: username }, (err, user)=>{
if(err) throw err;
if(!user){
req.flash('fail_msg', 'User not found');
return done(null, false, {message: "No user found"});
}
else{
bcrypt.compare(password, user.password, (err, isMatch)=>{
if(err) throw err;
if(isMatch){
req.flash('success_msg', 'You are login successfuly');
return done(null, user);
}
else{
req.flash('fail_msg', 'Username and password does not match');
return done(null, false);
}
});
}
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
function ensureAuthenticated(req, res, next){
console.log(req.isAuthenticated()) // this is giving me false
if(req.isAuthenticated()){
return next();
}
else{
console.log("inside not authenticated")
req.flash('fail_msg', 'You are not autherized');
res.redirect('./login');
}
}

我打印了req.session,它在成功登录后给我这些结果
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
flash: { success_msg: [ 'You are login successfuly' ] },
passport: { user: '5b1a7808385405277c7546a2' } }
为什么req.isAuthenticated()返回false,我应该如何检查具有上述会话数据的经过身份验证的用户?