How does passport.js deserializeUser decrypt the hashed session data?

Viewed 750

After a user logs in by sending a POST to say /login, then passport will attach a session cookie, so that a persistent session is established. This is done via the serializeUser function. Then express-session will use this function to generate a hash (computed using HMAC) and sends it over.

On the next request, passport somehow manages to decrypt the hashed string using deserializeUser function and retrieve the user data from that. How is this possible if express-session really hashes the string? Aren't hashes one-way-only functions? And if express-session doesn't hash the string, then isn't that a security vulnerability?

1 Answers

It is up to the application to provide serializeUser and deserializeUser.

The application should be able to securely perform deserializeUser because they can check each hash they receive (set and read by passport middleware through request.session; I think the responsible portions of interest may be these: https://github.com/expressjs/session/blob/master/index.js#L160 and https://github.com/jaredhanson/passport/blob/master/lib/sessionmanager.js#L18-L25 (or on the more recently maintained fork, https://github.com/passport-next/passport/blob/master/lib/sessionmanager.js#L21-L28 )) against a map they have stored in their own local database/file/service, having previously associated and stored such user session hashes along with the user name (and/or other specific session info).

The application doesn't need to store passwords on the server as raw text which is I think the main concern since an exposed server will reveal to hackers not only their data for that site but the passwords of users often reused at other sites. And hashing a user name is somewhat better for privacy as someone inspecting a user's cookies for an old session hash will not even know which user they are.

And there should be no security concern with middleware setting any session objects on the request object, as the choice and sequence of middleware is under the control of the application and not transmitted over the network.

Related