Session Management Best Practices

On this page
  1. What does secure session handling require?
  2. What are the common session attacks?
  3. Why does regeneration matter so much?

Sessions are how a stateless web remembers who you are between requests — and because a session is your identity for its lifetime, it is a prime target. Get session management right and stealing a password becomes far less useful; get it wrong and attackers hijack accounts without ever knowing a credential. The rules are well established and worth following exactly.

What does secure session handling require?#

A handful of properties, each closing a real attack:

  • Unpredictable IDs — long, from a CSPRNG, so they cannot be guessed or brute-forced.
  • Secure transport & storage — the ID lives in a cookie with HttpOnly, Secure, and SameSite.
  • Regeneration on login — issue a new ID at authentication to defeat session fixation.
  • Sensible expiry — both idle timeout and absolute lifetime.
  • Server-side invalidation — logout and password change must kill the session server-side.

What are the common session attacks?#

AttackCauseDefense
Session hijackingStolen ID (XSS, sniffing)HttpOnly, Secure, short lifetime
Session fixationReusing a pre-login IDRegenerate ID at login
Session predictionWeak, guessable IDsCSPRNG-generated IDs
Idle hijackNever-expiring sessionsIdle + absolute timeouts

Why does regeneration matter so much?#

Because it closes fixation cheaply. If the ID the user holds after login is different from the one before, an attacker who planted a known ID gains nothing. Regenerate on every privilege change, not just login.

Session management ties together cookies, authentication, and CSRF defense. More at the Web Security hub.

Frequently asked questions#

What makes a session ID secure?

A secure session ID is long, generated from a cryptographically secure random source so it cannot be guessed, and stored in a cookie marked HttpOnly, Secure, and SameSite. It should be meaningless — carrying no user data — and validated server-side on every request. Predictable or short IDs invite session guessing.

What is session fixation?

Session fixation is an attack where the attacker sets or knows a victim’s session ID before they log in, then rides that same session once the victim authenticates. The defense is simple: always issue a brand-new session ID at login (and at any privilege change), discarding the pre-login one.

Sources & further reading