desmondlee desmondlee - 4 months ago 16
Node.js Question

How does passport js stores user object in session?

I am using node/express with passport in my development. I came across an article which says:

Express loads the session data and attaches it to the req. As passport stores the serialised user in the session, the serialised user object can be found at req.session.passport.user.

But to my surprise, the value for sessionID stores in the browser cookies remain the same before and after login. So where does the serialised user object is stored? I thought that it was stored in the user sessionid cookie initially but it seems that this is not the case as i still can access my user object with req.session.passport.user

Raf Raf

So where does the serialised user object is stored?

In Short

The serialized user object is stored in req.user by PassportJS taken from req.session.passport.user (which is is populated by Express) with the help of Passport's deserializeUser method.

Express adds the id of the session object into a cookie on user's browser, which is sent back to express in a header on every request. Express then takes the id from the header and search the session store (i.e. Mongo or whatever) and find the entry and load it to req.session.

PassportJS uses the content of req.session to keep track of the authenticated user with the help of serializeUser and deserializeUser methods (for more information on workflow of serializeUser and deserializeUser see my answer in this SO question).

Express is responsible for creating the session. when does the sessions gets created? That is when Express do not detect a session cookie. So the order in which you organize your session and passport configs in your app or server.js file is very important. If you declare your session and passport configs above static directory configs then all requests for static content will also get a session, which is not good.

See my answer to this SO question, where I have mentioned about static content access as well as how to selectively apply passport to certain routes, rather than default (you might not need to authenticate all the routes - hence you could avoid unnecessary session store lookup and de-serialization by attaching session only to requests that map to secure URLS see below).

//selectively applying passport to only secure urls
app.use(function(req, res, next){
    passport.session()(req, res, next)
    next(); // do not invoke passport

There is one amazing tutorial that I highly recommend you to read up if you want to understand the workflow of PassportJS.