← Lessons

quiz vs the machine

Platinum1860

Frontend

Secure Auth Token Storage

The trade offs between localStorage and HttpOnly cookies for holding session and access tokens in the browser.

6 min read · advanced · beat Platinum to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is an HttpOnly cookie harder to steal via XSS?

2. What threat does using cookies reintroduce?

3. Why keep access tokens short lived?