session fixation attacks and how to prevent them
session fixation definition, attack scenario, regenerate on login, req.session.regenerate, session ID rotation, why pre-login sessions are dangerous
Session Fixation Attacks and Prevention
Session fixation lets an attacker reuse a session ID they planted before the victim logged in. Without protection, the session ID remains the same after authentication — the attacker already has it and gains full access.
Attack flow: attacker visits the site, gets a session ID, tricks the victim into using that same session ID (via URL parameter or cookie injection), victim logs in — the server maps the existing session ID to the authenticated user, attacker reuses their original session ID and is now authenticated as the victim.
The fix is one line — regenerate the session ID immediately after login:
app.post('/login', async (req, res) => {
const user = await authenticate(req.body.email, req.body.password);
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
// Regenerate session ID — critical security step
req.session.regenerate((err) => {
if (err) return res.status(500).json({ error: 'Session error' });
req.session.userId = user.id;
req.session.role = user.role;
res.json({ success: true });
});
});req.session.regenerate creates a new session ID, copies nothing from the old session, and sets the new session cookie. The old session ID (even if the attacker has it) is now a dead key in the session store.
Always call regenerate on privilege escalation — login, role change, sudo-mode activation — any time a session transitions from lower to higher trust.
