Passport.js - Error: failed to serialize user into session

≯℡__Kan透↙ 提交于 2019-12-02 14:05:23

It looks like you didn't implement passport.serializeUser and passport.deserializeUser. Try adding this:

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

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

If you decide not to use sessions, you could set the session to false

app.post('/login', passport.authenticate('local', {
  successRedirect: '/accessed',
  failureRedirect: '/access',
  session: false
}));

Sounds like you missed a part of the passportjs setup, specifically these two methods:

passport.serializeUser(function(user, done) {
    done(null, user._id);
    // if you use Model.id as your idAttribute maybe you'd want
    // done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

I added the bit about ._id vs. .id but this snippet is from the Configure Section of docs, give that another read and good luck :)

Here an working but still lazy way to use sessions and still "serialisize" the values.

var user_cache = {};

passport.serializeUser(function(user, next) {
  let id = user._id;
  user_cache[id] = user;
  next(null, id);
});

passport.deserializeUser(function(id, next) {
  next(null, user_cache[id]);
});

in case or weird errors just ask yourself: "Do I rlly set '_id' in my user object?" - in most cases you dont. So use a proper attribute as key.

Using Promise with serializeUser & deserializeUser:

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  // console.log(`id: ${id}`);
  User.findById(id)
    .then((user) => {
      done(null, user);
    })
    .catch((error) => {
      console.log(`Error: ${error}`);
    });
});

Please see my github repo for a full code example how to solve this issue.

in passport.use('local-login'...)/ or /('local-singup'...)

if err you have to return "false" err {return done(null, req.flash('megsign', 'Username already exists #!#'));} true {return done(null, false, req.flash('megsign', 'Username already exists #!#'));}

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