Cookie flags for session security

Authentication and authorization Junior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

Which Set-Cookie header is best for a session?

Options
Hint 1 of 1

Which header blocks script access, HTTP and cross-site sends?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A __Host-sid=…; Path=/; Secure; HttpOnly; SameSite=Lax

Correct. Unreadable by scripts, HTTPS only, not sent on cross-site POSTs, host-locked.

Each attribute closes one hole: HttpOnly keeps scripts out, Secure keeps it off plain HTTP, SameSite=Lax holds it back on cross-site POSTs, and the __Host- prefix forbids Domain so subdomains can't set or read it.

Why not the others?
  • B sid=…; Domain=.example.com. Sent to every subdomain and readable by scripts.
  • C sid=…; Secure; SameSite=None. Sent cross-site and readable by scripts.
  • D sid=…; HttpOnly. No Secure flag, so it can go over plain HTTP; with no SameSite, some browsers still send it cross-site (Chromium defaults to Lax).

30-second answer

HttpOnly stops JavaScript from reading it, so an XSS bug can't steal the session. Secure sends it only over HTTPS. SameSite=Lax (or Strict) stops browsers sending it on most cross-site requests, which blocks classic CSRF. Scope it tightly with Path and no broad Domain, give it a sensible lifetime, and use the __Host- prefix so it can only be set by your exact host over HTTPS.

Practise saying it · 30 s. No recording, just a timer

Secure session cookies.

Say your answer out loud, then check which of these points you covered:

  • HttpOnly vs XSS theft
  • Secure
  • SameSite vs CSRF
  • __Host- prefix
  • Rotate id at login

Deep dive

SameSite=Lax still sends the cookie on top-level GET navigations; keep GETs free of side effects.

SameSite=None requires Secure and is needed for legitimate cross-site embeds.

__Host- cookies must be Secure, have Path=/ and no Domain.

Regenerate the session id at login and privilege changes.

Common mistakes

  • Session cookies readable by JavaScript.
  • Domain=.example.com so every subdomain gets the session.
  • Relying on SameSite alone for CSRF on state-changing GETs.

Senior take & follow-ups

List each flag with the attack it blocks, then __Host- and session regeneration.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does the __Host- prefix enforce?

    Show hint

    Secure, Path=/, no Domain attribute.

  2. Does SameSite replace CSRF tokens?

    Show hint

    Lax covers most cases; tokens still help for sensitive actions and older browsers.

Suggest a fix if something here is wrong or out of date.