Token Storage Security
On this page
Threat Model First
- Token theft is usually an XSS problem.
- Session fixation and CSRF are common when cookies are used without defenses.
- Production rule: choose the simplest session model that meets requirements.
Storage Options
- HttpOnly cookie: not readable by JS, reduces XSS token exfiltration risk.
- Memory: token in memory, cleared on refresh, requires refresh strategy.
- localStorage: easy, but exposed to XSS and persistence increases risk.
Recommended Default: Cookie Based Session
- Use HttpOnly, Secure, SameSite cookies.
- Use CSRF defenses for state changing requests.
- Rotate and revoke sessions server side.
CSRF and Cookies
- SameSite reduces CSRF but is not always sufficient for all flows.
- Use CSRF tokens or double submit cookie patterns when needed.
- Verify Origin and Referer for sensitive endpoints where possible.
XSS and localStorage
- If an attacker runs JS, localStorage tokens are easy to steal.
- HttpOnly cookies reduce token theft but do not remove XSS impact.
- Primary control for XSS is strong input handling and CSP.
Operational Controls
- Short lived access tokens and rotating refresh tokens.
- Server side revocation and session invalidation.
- Device binding signals and anomaly detection for suspicious sessions.
- Audit logging for login, refresh, and logout events.
Failure Modes
- localStorage token theft from an XSS bug.
- CSRF on cookie sessions without proper defenses.
- Refresh token reuse not detected, enabling session takeover.
- Cache leaks exposing authenticated responses.
Production Checklist
- Prefer HttpOnly Secure SameSite cookies for sessions.
- Deploy CSP and input validation to reduce XSS risk.
- CSRF protections exist for state changing endpoints.
- Rotation and revocation are implemented and monitored.