How-To Guide

How to Prevent Session Fixation Attacks

Stop session fixation by rotating the session identifier on login and privilege change, binding it to the browser, and invalidating the old one.

On this page

  1. Introduction
  2. Understand the attack
  3. Rotate the identifier on login
  4. Rotate on privilege change too
  5. Invalidate the old session server-side
  6. Bind the session where it helps
  7. Test the fixation path
  8. Common pitfalls
  9. Conclusion

Introduction

Session fixation is a subtle attack on the gap between being anonymous and being logged in. If the session identifier issued before login is the same one used after login, an attacker who can plant that identifier in the victim’s browser — by setting a cookie from a sibling subdomain or tricking the victim into a crafted link — ends up knowing the identifier of an authenticated session. The fix is simple once understood: never let a pre-authentication identifier become authenticated.

This tutorial explains the attack, how to rotate the identifier on login and on privilege change, how to invalidate the old one, and how to bind the session to the browser where it helps. It ends with a test that plants an identifier and proves the post-login session does not use it.

Understand the attack

The attacker needs a way to make the victim’s browser use an identifier the attacker chose. Common vectors are a sibling subdomain that can set a cookie for the parent domain, a link or a redirect that carries a session id, and any script running on the same origin. Once the victim’s browser holds that identifier and then logs in, if the server does not change it, the attacker now holds the identifier of an authenticated session.

The root cause is treating the identifier alone as the session. If the identifier is the only thing standing between an attacker and the session, then controlling the identifier before login is like controlling the session after. The defense is to guarantee that the authenticated session’s identifier is one the attacker could not have known, which means issuing a fresh one at the moment of authentication.

Rotate the identifier on login

On a successful login, before establishing the authenticated state, generate a new session identifier, write the authenticated session data under the new identifier, set the new cookie, and delete the old session. The identifier the browser had before login is discarded; it was potentially known to an attacker and must never carry the authenticated session.

This rotation must be unconditional. Do not check whether an identifier already exists and reuse it; always issue a new one. Even if the application believes the identifier is secret, a rotated one is strictly safer and removes the need to reason about how the old one might have been planted. Make rotation part of the login routine so no path authenticates without it.

import { randomBytes } from 'node:crypto';

async function login(req, res, userId, oldSessionId) {
  const newSessionId = randomBytes(32).toString('base64url'); // fresh, unguessable
  await sessions.create(newSessionId, { userId });              // authenticated session
  if (oldSessionId) await sessions.destroy(oldSessionId);       // kill the pre-login id
  res.setHeader('Set-Cookie',
    'sid=' + newSessionId + '; Path=/; HttpOnly; Secure; SameSite=Lax');
  res.writeHead(204).end();
}

Rotate on privilege change too

Authentication is not the only privilege boundary. Elevating to an admin role, completing a password reset, or enabling two-factor authentication all raise the stakes of the session. Rotate the identifier again at each of those transitions, so an identifier that existed under lower privilege cannot be used to reach the higher one. An attacker who knew an identifier before a promotion does not get the promoted session.

Rotating too often hurts usability, so scope it to meaningful privilege changes, not every request. The rule is that whenever the session’s authority increases, the identifier changes. This is the same principle as the login rotation, applied wherever authority grows, and it keeps the invariant simple: an identifier never spans a privilege boundary.

async function escalate(prevSessionId, newClaims) {
  const newId = randomBytes(32).toString('base64url');
  await sessions.create(newId, newClaims);
  await sessions.destroy(prevSessionId);   // the lower-privilege id is now dead
  return newId;
}

Invalidate the old session server-side

Rotating only the cookie is not enough; the old session must be destroyed on the server. If the old identifier remains valid, an attacker holding it still has a live session, rotated cookie or not. Delete the old session record in the same transaction that creates the new one, or the window between them could leave both valid.

For a framework that stores sessions in a cache or a database, destroy is a delete of the old key. Keep the check atomic so a slow delete does not leave a gap. Also expire anonymous sessions that never authenticated after a short time, so a planted identifier that was never used to log in does not linger as a valid anonymous session.

Bind the session where it helps

Rotating on login defeats fixation, but an attacker who steals an authenticated identifier can still hijack the session. Binding the session to a property of the client, such as the user agent or a network range, can raise the cost of a stolen identifier, but it is a weak control: those properties can be replicated, and binding to IP breaks mobile clients that change networks. Use binding as a defense in depth with the limitations understood, not as the primary protection.

The stronger controls are the standard session protections: HttpOnly so script cannot read the identifier, Secure so it never travels in plaintext, SameSite to limit cross-site sending, and a short idle timeout so a stolen identifier expires. Together with rotation on privilege change, these make both fixation and theft harder, and none of them alone is sufficient.

Test the fixation path

Simulate the attack: obtain a session identifier before login, then log in while carrying it, and assert the post-login cookie is a different value and the planted identifier no longer resolves to a session. Assert that the pre-login identifier is invalidated server-side, not merely replaced in the cookie. Repeat for a privilege escalation and assert the same rotation.

PLANTED=$(curl -sD - -o /dev/null http://localhost:3000/ | awk -F'sid=' '/Set-Cookie/{print $2}' | cut -d';' -f1)
curl -s -D - -o /dev/null -b "sid=$PLANTED" -X POST -d 'user=a&pass=b' http://localhost:3000/login | grep -i set-cookie
# the new sid must differ from $PLANTED
curl -s -o /dev/null -w '%{http_code}\n' -b "sid=$PLANTED" http://localhost:3000/account  # expect 401

Common pitfalls

Reusing the pre-login identifier for the authenticated session, rotating the cookie without destroying the old session, skipping rotation on privilege change, relying on client-based binding as the primary defense, and leaving anonymous sessions valid indefinitely are the recurring mistakes. Unconditional rotation on login and privilege change, server-side invalidation, standard cookie flags, and timeouts address them.

Conclusion

Session fixation exploits the gap between anonymous and authenticated. Rotate the identifier unconditionally on login, destroy the old session server-side, rotate again on any privilege change, and layer the standard cookie protections. Self-check by planting an identifier, logging in, and asserting the post-login identifier differs and the planted one no longer works. Then an attacker who set a pre-login cookie learns nothing useful after the login.

Sources: OWASP: Session fixation, OWASP: Session management cheat sheet, MDN: Set-Cookie and session cookies.

FAQ

How does session fixation work?
An attacker who can set the victim's session cookie, through a subdomain, an injected link, or a shared context, plants a known identifier. If the application keeps that identifier after login, the attacker's pre-set cookie is now an authenticated session and the attacker knows it.
Does rotating on login cost anything?
It invalidates any state keyed to the old identifier, so put session data behind the new identifier or migrate it. The cost is small and the protection is essential, so rotate unconditionally on authentication.

Related Examples