Security Playbook
13 · Authentication & sessionsOWASP A07:20257 min read

Sessions and cookies: keeping users logged in safely

After login, a session cookie is the user's identity. Which cookie flags protect it from XSS, network sniffing and cross-site requests, and the session lifecycle rules that stop fixation and hijacking.

In one sentence

A session cookie is as good as a password while it's valid. Ship it as HttpOnly; Secure; SameSite=Lax, keep it short-lived, and rotate it on login and privilege changes.

The flags

HTTP is stateless, so after you log in the server gives your browser a random session ID in a cookie and looks it up on every request. Whoever has that value is you. The cookie's attributes decide who can read it and when the browser sends it.

Session cookie flags vs four attacks
SameSite
Set-Cookie header: session=8f3a…c21; SameSite=None; Max-Age=3600
Injected script reads document.cookie
✕ Stolen: the attacker copies the session
Login page opened over http:// on café Wi-Fi
✕ Stolen: cookie traveled in plain text
Evil site auto-submits a POST to your app
✕ Sent: the forged request is logged in
User clicks a link to your app from an email
✓ Sent: user arrives logged in (expected)
Good default for a session cookie: HttpOnly; Secure; SameSite=Lax, plus a short lifetime. Strict is safer but logs people out when they arrive from other sites.
Toggle the flags and see which of the four scenarios the cookie survives.
AttributeProtects against
HttpOnlyJavaScript (and so XSS) reading the cookie
SecureSending it over plain http:// where it can be sniffed
SameSite=Lax / StrictOther sites making requests with it (CSRF)
Max-Age / ExpiresA stolen cookie staying valid forever
__Host- prefixSubdomains overwriting it; forces Secure, Path=/ and no Domain

Session lifecycle

  • Rotate the ID on login (and on role changes). Otherwise an attacker who planted a session ID before login gets a logged-in one after: session fixation.
  • Idle and absolute timeouts: expire after 30 minutes of inactivity and after N days regardless.
  • Logout means server-side delete, not just clearing the cookie.
  • Re-authenticate for sensitive actions: changing email, password or payout details asks for the password or MFA again.
  • Show active sessions so users can sign out of devices they don't recognize.
Set-Cookie: __Host-session=8f3a2c…; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600

Key takeaways

  • 01Whoever holds a valid session cookie is the user.
  • 02Use HttpOnly, Secure, SameSite=Lax and a __Host- prefix.
  • 03Rotate the session ID on login and privilege changes.
  • 04Expire sessions, delete them on logout and re-authenticate for sensitive actions.

Check your understanding

1 of 3

Who is the user, as far as the server knows?

Related concepts