Passport.js重定向到| successRedirect:'/ profile'|但是req.isAuthenticated()返回false

时间:2017-01-02 11:55:52

标签: javascript node.js express passport.js passport-local

以下代码是由Node.js + Express + Passport.js开发的应用程序的一部分。有效用户会被重定向到/profile网址(successRedirect),但req.isAuthenticated会返回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
    });
})

1 个答案:

答案 0 :(得分:0)

在需要验证的每条路线上,您都应该使用passport.authenticate中间件,即:

app.get('/profile', passport.authenticate('local'), (req, res) => {
  console.log(req.user);
  console.log(req.isAuthenticated());
}

请参阅Passport documentation