Authentication, Token Storage and CSRF

Where to keep sessions and tokens, why HttpOnly cookies are usually safest, and how CSRF attacks and defences work.

Advanced · about 4 hours · difficulty 4/5

Learn first: Cross-Site Scripting (XSS) Prevention

Almost every app has login, and the frontend decides where credentials live. The choice determines which attacks can steal them.

Storing credentials

  • HttpOnly, Secure, SameSite cookies holding a session id or token: JavaScript cannot read them, so an XSS bug cannot exfiltrate them directly. This is the usual recommendation for browser apps.
  • localStorage or sessionStorage with a JWT: simple, but any script on the page (including XSS or a compromised dependency) can read and steal it. Avoid for long-lived tokens.
  • In-memory tokens with a refresh token in an HttpOnly cookie: a common SPA pattern that limits exposure.
  • A backend-for-frontend (BFF) keeps third-party OAuth tokens on the server entirely.

CSRF

Cross-Site Request Forgery tricks a logged-in user's browser into sending a state-changing request to your site from another site, because cookies are attached automatically. Defences:

  • SameSite=Lax (the modern default) or Strict cookies block most cross-site sends.
  • CSRF tokens or checking the Origin header on the server for state-changing requests.
  • Never change state with GET requests.

OAuth and third-party login

Use the Authorization Code flow with PKCE for SPAs and mobile, via a well-tested library or provider (Auth.js, Clerk, Auth0, Supabase, Firebase). Do not roll your own crypto or token parsing.

Frontend auth UX that stays secure

Hide UI the user cannot use, but always enforce permissions on the server. Handle expiry by refreshing once and then redirecting to login, clear client caches on logout and avoid putting tokens in URLs (they leak through history, logs and referrers).

Good enough to move on

You can argue for a storage choice with its trade-offs, explain a CSRF attack step by step and how SameSite and tokens stop it, and wire up an OAuth login with PKCE using a library.

Key concepts

  • Sessions vs JWTs
  • HttpOnly cookies vs localStorage
  • Refresh tokens and expiry handling
  • CSRF attacks and SameSite
  • CSRF tokens and Origin checks
  • OAuth 2.0 with PKCE
  • Auth providers and libraries
  • Backend-for-frontend pattern

Mini project

Implement login for a React app using an HttpOnly session cookie from a small backend (or an auth provider), with protected routes, silent refresh, logout that clears the query cache and a CSRF defence you can explain.

Check yourself

If your app has an XSS bug, why is a token in localStorage worse than one in an HttpOnly cookie, and what can the attacker still do in both cases?

Free resources