Passport login and persisting session

前端 未结 5 1060
悲哀的现实
悲哀的现实 2020-12-22 22:11

Background

I have a MEAN application with CRUD capabilities fully tested with postman. I have been trying to persist login for quite some time now with no luck. I

5条回答
  •  我在风中等你
    2020-12-22 22:23

    As @hassansin says you need to use a middleware that implement session management. The passport.session() middleware is to connect the passport framework to the session management and do not implement session by itself. You can use the express-session middleware to implement session management. You need to modify your auth.js in the following way

    var passport = require('passport');
    var session = require('express-session');
    var LocalStrategy = require('passport-local').Strategy;
    
    module.exports = function(app, user){
      app.use(session({secret: 'some secret value, changeme'}));    
    
      app.use(passport.initialize());
      app.use(passport.session());
    
      // passport config
      passport.use(new LocalStrategy(user.authenticate()));
    
      passport.serializeUser(function(user, done) {
        console.log('serializing user: ');
        console.log(user);
        done(null, user._id);
      });
    
      passport.deserializeUser(function(id, done) {
        user.findById(id, function(err, user) {
          console.log('no im not serial');
          done(err, user);
        });
      });
    };
    

    Notice that in this case the session engine is using the in memory store and it didn't work if you scale your application and apply load balancing. When you reach this development state something like the connect-redis session store will be needed.

    Also notice that you need to change the secret value used on the session midleware call and use the same value on all application instances.

提交回复
热议问题