Passport.js redirects to |successRedirect: '/profile'| but req.isAuthenticated() returns false

a 夏天 提交于 2019-12-04 05:31:33

问题


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
    });
})

回答1:


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());
}

see Passport documentation



来源:https://stackoverflow.com/questions/41426381/passport-js-redirects-to-successredirect-profile-but-req-isauthenticated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!