tezvyn:

localStorage vs httpOnly cookie for auth tokens

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

Token storage security trade-offs.

OUTLINE

localStorage is JS-readable so XSS steals it; httpOnly cookies are JS-invisible blocking XSS theft but exposed to CSRF, mitigated by SameSite and tokens.

WHAT THIS TESTS Your ability to map storage choices to concrete threat models, specifically cross-site scripting and cross-site request forgery, rather than reciting a one-line preference.

A GOOD ANSWER COVERS localStorage is a key-value store readable and writable by any script on the origin. That makes the token trivially exfiltrated if an attacker lands any XSS payload, since they can read it and post it elsewhere. However, localStorage is never sent automatically with requests, so it is inherently immune to CSRF; the app must attach the token manually in an Authorization header. An httpOnly cookie, by contrast, is invisible to document.cookie and JavaScript, so an XSS payload cannot directly read it, which is its main advantage. The cost is that browsers attach cookies automatically to matching requests, which is exactly the condition CSRF exploits. You mitigate CSRF with the SameSite attribute set to Lax or Strict, anti-CSRF tokens, and origin checks, and you always add Secure so it only travels over HTTPS.

COMMON WRONG ANSWERS Saying httpOnly cookies are completely safe, ignoring CSRF. Saying localStorage is fine because HTTPS encrypts it, which misses XSS. Swapping the threats, claiming localStorage is vulnerable to CSRF. Forgetting that XSS can still ride along a cookie by making authenticated requests even without reading it.

LIKELY FOLLOW-UPS How does SameSite mitigate CSRF and where does it fall short? Can XSS still abuse an httpOnly cookie? What is the double-submit cookie pattern? Where do refresh tokens belong?

ONE CONCRETE EXAMPLE A comment widget has an XSS hole. If the JWT sits in localStorage, the injected script reads it and ships it to an attacker server, fully compromising the account anywhere. If the same token lived in an httpOnly Secure SameSite=Strict cookie, the script could not read it; the attacker could only trigger same-origin authenticated actions, and SameSite plus a CSRF token blunts cross-site forgery, sharply narrowing the blast radius.

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.