Node+Passport.js + Sessions + multiple servers

不打扰是莪最后的温柔 提交于 2019-12-21 20:45:18

问题


Passport is great. I now discovered that I have some problem with how it handles sessions. I must be using it wrong.

All works well for me with login + sessions + user data I store in my database. However I find that when I move to production environment (cloud on EC2 with multiple servers), I lose the login session each time. This is now clear to me - probably happens since the session is unique to each server.

So my question is - how do I get around this.. I guess I will need to store my own cookie on the user's browser?

Does this mean that I cannot use express.session at all?

Thanks, Ilan


回答1:


OK, So basically what I was looking for (not sure it would be the same answer for everyone else) was a way to store session data between loadbalanced instances without making a DB call for every page view, which seems excessive to me, since I just need to keep the user signed in to Google/FB.

It seems that the answer I was looking for was the cookie-session middleware https://github.com/expressjs/cookie-session

This needs to replace the default express.session mechanism which uses MemoryStore. BTW MemoryStore itself gives you a warning when run that it will not scale past a single process, and also that it may cause a memory leak.

Which if I understand correctly is serializing the session data itself into the session cookie (encrypted) instead of just using a session ID in the session cookie. This seems perfect to me. Obviously I don't expect it to work if you have a lot of session data, since a cookie is limited in size. In my case, I just needed the name, ID and avatar url, so I think this will suffice. Thanks for everyone who helped.




回答2:


You need to store your session data in a 'global' area, that is accessible to all your servers. This could be redis or another DB.

Take the example from MEAN.JS. Here they use express-session with a MongoDB storage container (since they are a MEAN stack ; ), via connect-mongo. Their project is super easy to set up, if just for an example.

Code while setting up express is like this:

//top of file
var session = require( 'express-session' )
    mongoStore = require( 'connect-mongo' )( {
        session: session
    } );

//...later in setup

// Express MongoDB session storage
app.use( session( {
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    store: new mongoStore( {
        db: db.connection.db,
        collection: config.sessionCollection
    } )
} ) );

// use passport session
app.use( passport.initialize() );
app.use( passport.session() );


来源:https://stackoverflow.com/questions/26026077/nodepassport-js-sessions-multiple-servers

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