Erik
Erik

Reputation: 14770

nodejs/express. regenerate session

I have a simple nodejs/express application. To save user authentication I use:

req.session.auth = user;

but this I've found regenerate method:

req.session.regenerate(function (err) {
   req.session.auth = user;
});

My question is: should I use regenerate method or just req.session.auth = user;

Upvotes: 13

Views: 14852

Answers (2)

the Radek
the Radek

Reputation: 190

In fact, you should always use req.session.regenerate after user authentication to prevent session fixation attacks.

According to MDN, the session cookie should be always regenerated after user authentication. To do this, you must internally change the session ID by regenerating the session.

If your site authenticates users, it should regenerate and resend session cookies, even ones that already exist, whenever a user authenticates. This approach helps prevent session fixation attacks, where a third party can reuse a user's session.

If you want/need to keep some variables from the previous session, you will need to copy them manually.

let session = req.session;
req.session.regenerate(function (err) {
    req.session.auth = user;
    req.session.some_var = session.some_var;
});

More information about the session fixation attack can be found here https://owasp.org/www-community/attacks/Session_fixation.

Upvotes: 1

Rohan Singh
Rohan Singh

Reputation: 21535

I would lean toward the req.session.regenerate, but it depends on what you're trying to do. If you just do req.session.auth = user, then you will save the auth to the session. However, if you use regenerate, you will actually be clearing the entire session and then saving the auth.

The difference is that with the first approach, any other session variables in the current session will persist. It's up to you to figure out if that makes sense for your site, or if you would rather have the session be clean once authentication is complete.

Upvotes: 19

Related Questions