ekinrf ekinrf - 19 days ago 6
Node.js Question

PassportJS Node: why need serializeUser and deserializeUser even when not using session?

exports.initPassportLocalStrategy = function () {
passport.use(new LocalStrategy(
{
session: false
},
function(username, password, done) {
UserProxy.validateUserWithPassword(username, password)
.then(function (user) {
if(user) done(null, user);
else done(null, false);
})
.catch(done);
}
));

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


I'm implementing a token based auth middleware without seesion. So I was wondering why do I need to provide a
serialzeUser
function? I have read that the reason is to put user or some of its properties into the session and then
desearlizeUser
would retrieve the whole object from the session and put it in the
req.user
.

So here are my questions:


  1. Why can't the done(null, user); in the
    LocalStrategy
    function put the user into
    req.user
    ? Why even bother serialise and deserailie?

  2. If remove the
    searlizeUser
    function I will get an error, but I can get away without a
    deserilzeUser
    function, why? And in this case, who puts the user object to
    req.user
    ?



Many thanks.

Answer

You don't need serialize/deserialize. Your setup is slightly wrong. You need to move the session: false out of the strategy and into passport.authenticate. This is because strategies can't decide this, it's rather dependent on your route which kind of authentication you want.

passport.use(new LocalStrategy(
  function(username, password, done) {
    UserProxy.validateUserWithPassword(username, password)
      .then(function (user) {
        if(user) done(null, user);
        else done(null, false);
      })
      .catch(done);
  }
));
app.use(passport.initialize());  
app.post('/auth', passport.authenticate(  
  'local', {
     session: false // here goes the session false
  }), doWhateverYourSetupNeeds);