mediumSessions

Login Keeps the Session Id From Before Login

The session id is not rotated when the visitor logs in.

Why it matters

Session ids are handed out before login. If an attacker can plant one in a victim's browser, for example through a link on a shared machine or a subdomain, they wait for the victim to log in and then use the same id. Regenerating the session at login gives the logged-in user a fresh id the attacker never saw. It is one call.

What it looks like

This is the shape of code that triggers the rule. AI tools produce it because it works, and nothing tells them it is unsafe.

Express login writes the user id into the existing session
const express = require('express');
const app = express();
app.post('/login', async (req, res) => {
  const user = await users.findByEmail(req.body.email);
  if (!user || !(await bcrypt.compare(req.body.password, user.passwordHash))) return res.status(401).end();
  req.session.userId = user.id;
  res.redirect('/dashboard');
});

The smallest fix

minimal patch
// After the password check succeeds:
req.session.regenerate((err) => {
  if (err) return next(err);
  req.session.userId = user.id;
  req.session.save(() => res.redirect('/dashboard'));
});

The better fix

If you have a few more minutes, this is the approach that holds up as the app grows.

safe alternative
// Passport's req.logIn() and most auth libraries (NextAuth, Lucia,
// iron-session) rotate the session for you. On logout call
// req.session.destroy() so the id cannot be reused either.

Let your AI tool fix it

When the scanner finds this in your project, it fills in the file and line for you. This is the prompt it gives you to paste into Claude Code, Cursor or whatever you use.

In [the file] at line [the line number] the user is written into the session without rotating the session id: [the flagged code]. Wrap the assignment in req.session.regenerate() so a fresh id is issued at login, and call req.session.destroy() on logout. Keep the redirect and the rest of the flow the same.

How to check the fix worked

1. Note the session cookie value before login, log in, and confirm the
   cookie value changed.
2. Confirm the old cookie value is no longer accepted.

Further reading