What it is
Choosing where to keep an authentication token in the browser is a security trade off between two threats: cross site scripting and cross site request forgery.
The options
- localStorage is readable by any JavaScript on the page. If XSS happens, the token is stolen instantly. It is not sent automatically, so CSRF is not a direct concern.
- HttpOnly cookie cannot be read by JavaScript, so XSS cannot exfiltrate it directly. But it is sent automatically, which opens CSRF.
A balanced approach
- Store the token in an HttpOnly Secure cookie to resist XSS theft.
- Add SameSite and CSRF tokens to close the CSRF gap.
- Keep access tokens short lived and refresh them so a leaked token expires fast.
Why XSS dominates
If an attacker has XSS they can act as the user regardless of storage, but reading a raw token also lets them use it elsewhere. Limiting token readability and lifetime reduces that damage.
Key idea
HttpOnly Secure cookies with SameSite and short lifetimes resist XSS token theft while CSRF defenses close the cookie gap.