Passport.js redirects to |successRedirect: '/p

2019-02-28 02:02发布

问题:

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