For a browser web app, where is a session/auth token safest from XSS theft?
Options
- In localStorage, where scripts of the page can read it
- In a global JavaScript variable inside the page
- In an HttpOnly, Secure, SameSite cookie (Correct option)
- In the URL query string of each request
Answer
An HttpOnly, Secure, SameSite cookie
Why
If an attacker injects JavaScript into your page (XSS), that script can read localStorage and JS variables and send your token away.
An HttpOnly cookie cannot be read by JavaScript at all; the browser just sends it with requests. Secure = only over HTTPS; SameSite = not sent on most cross-site requests.
Cookies need CSRF protection, which SameSite mostly provides.
Remember
Auth token in a browser → HttpOnly + Secure + SameSite cookie.