简体   繁体   中英

Session lost with passport.js

I manage to log in with passport.js

    app.post('/login', passport.authenticate('local'), function(req, res) {
        res.cookie('username', req.user.username);
        res.redirect('/');
    });

but after that my session seems lost.

    app.post('/user/favorites', function(req, res) {
    // `req.user` contains the authenticated user.

    console.log(req.user); // Undefined
    if(req.isAuthenticated()) { // false
        console.log('HI');
    }
});

Instead of setting the user cookie manually, let passport do it for you

req.logIn(user, function(err) {
  if (err) { return next(err); }
  return res.redirect('/users/' + user.username);
});

replace your cookie line with this.

Source: http://passportjs.org/guide/authenticate/ (see custom callback section)

Have you followed the instructions given in documentation, try(if not already done)

passport.serializeUser(function(user, done) {
    done(null, user);
});
passport.deserializeUser(function(user, done) {
    done(null, user);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM