tezvyn:

JWT storage: localStorage versus HttpOnly cookie

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

Reasoning about XSS/CSRF trade-offs in token storage.

OUTLINE

localStorage is JS-readable so XSS steals the token; HttpOnly cookies resist XSS theft but reintroduce CSRF, mitigated by SameSite plus CSRF tokens.

WHAT THIS TESTS: Whether you can articulate that neither storage location is free, and that the choice is a trade-off between XSS exfiltration and CSRF that must be paired with mitigations.

A GOOD ANSWER COVERS: localStorage is readable and writable by any JavaScript running on the page, so if the app has any XSS vulnerability, the attacker's injected script can read the JWT and send it anywhere, fully compromising the session; localStorage is immune to CSRF only because the token is not auto-attached, but that XSS exposure is severe. An HttpOnly cookie cannot be read by JavaScript, so XSS cannot directly steal it; the browser attaches it automatically, which is convenient but means a forged cross-site request would carry it, reintroducing CSRF. You mitigate that with the SameSite attribute (Lax or Strict) and, for sensitive actions, a synchronizer or double-submit CSRF token, plus the Secure flag to require HTTPS. The generally recommended posture is to store the token in an HttpOnly, Secure, SameSite cookie and layer CSRF defenses, because XSS-driven token theft tends to be the more catastrophic and harder-to-contain failure, and because robust CSRF mitigations are well understood. Either way, keep access tokens short-lived and use refresh-token rotation.

COMMON WRONG ANSWERS: Saying localStorage is fine because the app has no XSS (you cannot guarantee that); saying HttpOnly cookies are completely safe and ignoring CSRF; thinking one mechanism eliminates the need for short token lifetimes; conflating HttpOnly with Secure.

LIKELY FOLLOW-UPS: How does SameSite=Strict break legitimate cross-site flows, and when is Lax preferred? Why combine HttpOnly cookies with a CSRF token? How do refresh-token rotation and short expiries reduce blast radius?

ONE CONCRETE EXAMPLE: A team stores the JWT in localStorage; a single XSS in a third-party script reads it and silently exfiltrates every user's token. Switching to an HttpOnly, Secure, SameSite=Lax cookie with a CSRF token means the same XSS can no longer read the token, and forged cross-site posts are rejected for lacking the CSRF token.

Read the original → cheatsheetseries.owasp.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.