Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

persistent sessions with passport, mongodb and express

I'm using passport to handle authentication and sessions in my application. I'm persisting sessions to mongodb using mongostore.

The setup works fine in general. However, when I restart the server all users are logged out, so apparently sessions are hold in memory instead of being only persisted to mongodb. I'm trying to achieve a setup where users are still logged in when restarting the server.

Basic configuration is as follows

middleware

    app.use(express.cookieParser('your secret here'));
    app.use(express.session());
    app.use(passport.initialize());
    app.use(passport.session({
        maxAge: new Date(Date.now() + 3600000),
        store: new MongoStore(
            {
                db: mongodb.Db(
                    conf.mongodbName,
                    new mongodb.Server(
                        'localhost',
                        27017,
                        {
                            auto_reconnect: true,
                            native_parser: true
                        }
                    ),
                    {
                        journal: true
                    }
                )
            },
            function(error) {
                if(error) {
                    return console.error('Failed connecting mongostore for storing session data. %s', error.stack);
                }
                return console.log('Connected mongostore for storing session data');
            }
        )
    }));

passport

passport.use(new LocalStrategy(
    {
        usernameField: 'email',
        passwordField: 'password'
    },
    function(email, password, done) {
        console.log('user %s attempting to authenticated', email);
        return User.findOne({email:email}, function(error, user) {
            if(error) {
                console.error('Failed saving user %s. %s', user.id, error.stack);
                return done(error);
            }
            if(!user) {
                return done(null, false);
            }
            console.log('user %s logged in successfully', user.id);
            return done(null, { //passed to callback of passport.serializeUser
                id : user.id
            });
        });
    }
));

passport.serializeUser(function(user, done) {
    return done(null, user.id); //this is the 'user' property saved in req.session.passport.user
});

passport.deserializeUser(function (id, done) {
    return User.findOne({ id: id }, function (error, user) {
        return done(error, user);
    });
});

github repo (including all code necessary to run code)

I created a barebone github repo including the code here

just create a conf.js file in the root directory with your mongodb credentials, i.e. mongodbURL and mongodbName, run npm install and node app.js to get started.

thanks

like image 784
forste Avatar asked Apr 17 '13 13:04

forste


People also ask

Does passport require Express session?

Now, one thing to note here is that Passport works on top of the express session. So you have to use the express session middleware before using Passport middleware. Once you've set up the middleware, your passport strategy will come into the picture, which will be looking like this.

What is passport Localstrategy?

passport-local is the strategy you would use if you are authenticating against a username and password stored 'locally' i.e. in the database of your app - 'local' means local to your application server, not local to the end user. passport-jwt is the strategy for using JSON Web Tokens.

What is passport session?

passport. session() acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.


1 Answers

passport.session() doesn't take any configuration, as of Express version 4.X it's session() you need to configure:

app.use(session({
  cookie : {
    maxAge: 3600000 // see below
  },
  store : new MongoStore(...)
});
...
app.use(passport.session());

Also, maxAge (which should be a property of cookie) doesn't take a Date argument, but just the number of milliseconds a session should be valid.

For instructions on using the express middleware module session, you can find out more here.

like image 112
robertklep Avatar answered Sep 20 '22 02:09

robertklep