Skip to the page

Authentication and authorization · mid

Cookies, CSRF and session security

Session cookies should be HttpOnly, Secure and SameSite (ideally with the __Host- prefix), and because browsers attach cookies to cross-site requests automatically, cookie-based auth also needs CSRF protection for state-changing requests.

The notes

What you must know

  • HttpOnly: JavaScript cannot read the cookie (limits XSS theft). Secure: HTTPS only. SameSite=Strict or Lax: not sent on most cross-site requests (Lax still sends on top-level GET navigations). SameSite=None requires Secure.
  • __Host- prefix: the browser only accepts it with Secure, Path=/ and no Domain, so subdomains cannot set or read it. OWASP recommends it for session ids. Leave Domain unset.
  • CSRF: another site makes the user's browser send a request to your API with their cookies. Defences: SameSite cookies, CSRF tokens (synchronizer or double-submit), checking Origin/Referer on state-changing requests, and requiring a custom header (which forces a CORS preflight).
  • GET must never change state; otherwise a link or image tag can trigger it.
  • Session fixation: always issue a new session id after login or any privilege change, and delete the old one.
  • Timeouts: idle timeout (OWASP: 2-5 minutes for high-value apps, 15-30 for low-risk) and absolute timeout; enforce them on the server. Logout must invalidate the session on the server, not just clear the cookie.
  • Bearer tokens in an Authorization header are not sent automatically, so they are not CSRF-prone, but JavaScript can read them, so XSS can steal them.

The red pen

Common traps: mistake → fix

  • Mistake: CORS protects against CSRF

    Fix: CORS controls reading responses; a simple cross-site form POST is still sent with cookies.

  • Mistake: SameSite=Lax makes CSRF impossible

    Fix: Lax still allows top-level GET navigations, and same-site subdomains count as same-site; keep tokens or Origin checks for sensitive actions.

  • Mistake: Clearing the cookie logs the user out

    Fix: a stolen copy of the session id still works until the server invalidates it.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which cookie attributes do you set on a session cookie, and why each?
  2. What is CSRF? How do you prevent it with cookie-based auth?
  3. Does SameSite solve CSRF completely?
  4. What is session fixation?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview