What is session fixation and how do you prevent it?
Session fixation is an attack where an attacker sets a known session ID on the victim's browser before they log in. After the victim authenticates, the server upgrades their session to authenticated — but the attacker already knows the session ID and can now hijack the authenticated session.
Classic attack:
- Attacker visits the login page and receives a session cookie (e.g.
JSESSIONID=ABC123). - Attacker tricks the victim into clicking a crafted link that sets the same cookie value (e.g. via a URL parameter
?sessionid=ABC123if the app accepts session IDs from the URL). - Victim logs in — the app marks session
ABC123as authenticated. - Attacker uses the pre-known
ABC123and is now authenticated as the victim.
Prevention: Issue a completely new session ID on every login — this is the primary defense. Old pre-authentication session data should be discarded or migrated. Never accept session IDs from URL parameters. Set HttpOnly + Secure + SameSite on session cookies. Most modern frameworks handle this automatically (session.regenerate() in Node/Passport, Spring Security's sessionManagement().sessionFixation().newSession()).