16. Web Authentication

Sessions, tokens, cookies, and keeping logins safe in the browser

Imagine a busy coat check at a theatre. You hand over your coat, and in return you get a little numbered ticket. When you come back at intermission, you don't have to prove the coat is yours or describe it in detail — you just show the ticket, and the attendant fetches the right coat. The ticket is small, it means nothing to anyone else, and the real record of what belongs to whom lives behind the counter.

That little ticket is the whole problem of web authentication in miniature. A web server, like the coat-check attendant, talks to thousands of people at once and has a famously bad memory: by design, it forgets you the instant it finishes answering your request. So how does a backend know that the request asking to "transfer $500 from my account" is coming from the person who logged in a minute ago, and not from a stranger — or an attacker?

This article is about getting that right. We'll assume you've already met hashing, password hashing and KDFs, and digital signatures earlier in this series — those are the primitives. Here we're building the system: how a browser and a backend agree on who you are, where the proof of that lives, and which storage choices quietly expose you to attack. Part two, Hardening Web Auth, goes deeper into JWTs, OAuth, and revocation.

Authentication vs Authorization

These two words get blurred together constantly, but they answer different questions:

Authentication (authn)

"Who are you?"

Proving identity. You type a password, tap a hardware key, or scan a fingerprint. The system confirms you are Alice.

Authorization (authz)

"What are you allowed to do?"

Deciding permissions. Alice is authenticated — but is she allowed to delete this document, or read that user's records?

Authentication happens once (at login); authorization happens on every request, because every request touches different resources. This article is mostly about authentication and, crucially, about how the answer to "who are you?" is carried forward to every subsequent request so the backend can make authorization decisions. That carrying-forward is the hard part.

The Core Problem: HTTP Forgets You

HTTP is stateless. Each request arrives as a self-contained envelope — a method, a URL, some headers, maybe a body — and when the server finishes responding, it retains nothing about you. The next request from your browser looks, to the server, like it came from a total stranger.

That's wonderful for scaling (any server in a fleet can handle any request) and terrible for logins. If the server forgets you after every request, then every request has to re-establish who you are. You obviously can't send your password on every click. So the login step trades your password for something reusable — a credential the browser attaches to each subsequent request. The whole design space of web auth is about what that credential is, where it lives, and how it's protected.

The one idea to hold onto

Login converts a secret you know (a password) into a token you carry (a session ID or a bearer token). Every design decision that follows is about protecting that carried token, because from the server's point of view, whoever holds it is you.

Two Models: Sessions vs Tokens

There are two dominant answers to "what does the browser carry, and what does the server check?" They sit at opposite ends of a spectrum from stateful to stateless.

Server-side sessions (stateful)

The coat-check model. When Alice logs in, the server generates a large random session ID, stores a record server-side — session 7f3a… → {user: alice, expires: …} — and sends only the opaque ID back to the browser. The ID itself means nothing; it's just a lookup key. On each request the server takes the ID, looks up the record, and learns who Alice is.

A session ID is just a random lookup key

Browser holds:   sid = 7f3a9c2e15b84d0af6...   (opaque, ~128 bits of randomness)

Server stores: 7f3a9c2e15b84d0af6... → { user: "alice", roles: ["editor"], createdAt: 1720224000, expiresAt: 1720310400 }

The ID must be unguessable — generated from a cryptographically secure random source with enough entropy (128 bits is the usual floor) that an attacker can't brute-force a valid one. Beyond that, it carries no information and needs no signature: all the trust lives in the server's own store.

Stateless bearer tokens

Here the server issues a self-contained token that encodes the claims itself — "this is alice, an editor, valid until 3pm" — and signs it with a secret only the server knows. The browser sends the token back on each request; the server verifies the signature and reads the claims straight out of the token. No server-side lookup, no shared session store. The token is a bearer token: possession is proof. The dominant format is the JWT, which Part 2 dissects byte by byte.

Server-side session

  • Token is an opaque ID; all state lives on the server.
  • Every request costs a session-store lookup (memory/Redis/DB).
  • Revocation is trivial: delete the record and the session is instantly dead.
  • Sharing state across a server fleet needs a shared store.
  • Great default for classic web apps and anything needing instant logout.

Stateless token

  • Token is self-describing and signed; the server keeps no per-session state.
  • Verification is a local signature check — no lookup, scales horizontally for free.
  • Revocation is hard: a valid signature is valid until it expires.
  • Ideal for APIs, microservices, and cross-service delegation.
  • You pay for statelessness with weaker revocation — see Part 2.

The tradeoff is genuinely fundamental and there's no free lunch: sessions make revocation easy and scaling harder; tokens make scaling easy and revocation harder. A rule of thumb — if you can afford a session store and you value instant logout (banking, admin panels), prefer sessions. If you're building an API consumed by many services or want stateless horizontal scaling, tokens earn their keep. Plenty of real systems use both: a stateless access token for speed plus a stateful refresh token you can revoke, which we get to below.

Where the Credential Lives in the Browser

Whatever the credential is, the browser has to store it somewhere and attach it to requests. There are two realistic homes, and choosing between them is a security decision, not a convenience one.

Cookies

A cookie is a small value the browser stores per-origin and — this is the key part — attaches automatically to every request to that origin. You set it once with Set-Cookie and the browser handles the rest. Cookies carry three security attributes that matter enormously:

  1. HttpOnly

    The cookie is invisible to JavaScript. document.cookie can't read it. This is the single most important defense against token theft: if an attacker runs script in your page, they still can't exfiltrate an HttpOnly cookie.

  2. Secure

    The cookie is only ever sent over HTTPS, never plain HTTP. This stops a network eavesdropper from lifting it off the wire. (See the TLS article for why the wire is otherwise readable.)

  3. SameSite

    Controls whether the cookie is attached to cross-site requests. Strict never sends it cross-site; Lax (the modern browser default) sends it only on top-level navigations; None always sends it (and then requires Secure). This is the front line against CSRF, below.

localStorage / JavaScript memory

The alternative is to hand the token to JavaScript and let your app code store it in localStorage, sessionStorage, or an in-memory variable, then attach it manually to each request in an Authorization: Bearer … header.

This is convenient — it's just a string your code controls, easy to send to a different API domain — but it comes with a hard rule: anything JavaScript can read, malicious JavaScript can steal. localStorage has no HttpOnly equivalent. If an attacker gets script running on your page, a token in localStorage is theirs in one line.

The storage decision in one sentence

An HttpOnly cookie is safe from script theft but automatically attached (so you must defend against CSRF); a localStorage token is immune to CSRF (nothing is sent automatically) but fully exposed to XSS. You are choosing which class of attack you have to defend against.

To make that concrete we need to meet the two attacks by name.

The Two Attacks: XSS and CSRF

These are the reason the storage choice matters. We describe them here strictly to justify the defenses — the point is to build the right walls, not to break in.

XSS — Cross-Site Scripting

XSS is when an attacker manages to run their JavaScript inside your page's origin — typically because the app rendered untrusted input without escaping it, or pulled in a compromised dependency. Once their script runs, it has all the powers your own code has: reading the DOM, making requests as the logged-in user, and — the relevant part here — reading anything JavaScript can read.

Token in localStorage

XSS wins. localStorage.getItem('token') hands the attacker your credential, which they ship to their own server. Full account takeover.

Token in an HttpOnly cookie

XSS can still act as you while the page is open, but it cannot read the cookie to steal it. The credential can't be exfiltrated and reused elsewhere. Damage is contained.

So HttpOnly cookies blunt the theft half of XSS. (Nothing but eliminating the XSS itself — output encoding, a strong Content-Security-Policy, careful dependencies — stops an attacker from acting within an open session. XSS is always a serious bug; HttpOnly just denies the attacker a portable, reusable key to your account.)

CSRF — Cross-Site Request Forgery

CSRF exploits the automatic attachment of cookies. Suppose your bank stores its session in a cookie. You're logged in, and in another tab you visit a malicious page. That page contains a hidden form that POSTs to yourbank.com/transfer. Because the request goes to your bank's origin, the browser helpfully attaches your bank cookie — and the transfer goes through. You never clicked anything meaningful. The attacker never saw your cookie; they just borrowed the browser's reflex to send it.

Notice the asymmetry: CSRF only works because cookies are sent automatically. A token in localStorage is immune to CSRF by construction — the attacker's page can't read it, and it isn't attached automatically, so a forged cross-site request simply arrives with no credential.

There are two solid defenses for cookie-based auth:

  1. SameSite cookies

    Setting SameSite=Lax or Strict tells the browser not to attach the cookie on the cross-site request the attacker's page triggered. The forged request arrives with no cookie and is rejected. Lax is the modern default and blocks the classic hidden-form POST attack.

  2. Anti-CSRF tokens

    The server embeds an unpredictable per-session token in your page (a hidden field or a readable, non-HttpOnly cookie the JS echoes back in a header — the double-submit pattern). A legitimate request carries it; the attacker's cross-site page can't read it, so it can't forge one.

The clean summary

HttpOnly defeats XSS token theft. SameSite and anti-CSRF tokens defeat CSRF. Cookies expose you to CSRF but let you shut XSS theft down; localStorage is immune to CSRF but wide open to XSS. For most apps the HttpOnly-cookie side of that trade is the safer default, because a good CSRF defense is a well-understood checkbox, whereas guaranteeing zero XSS forever is not.

Storage attack sandbox

A purely simulated sandbox — no real network, no real exploit code. Choose where the credential lives, set the cookie flags, then fire a simulated XSS (injected script trying to read the credential) or CSRF (a forged cross-site request) and see which attack the configuration blocks, and why.

Cookie flags

The Login Flow, and Why Tokens Are Short-Lived

Let's assemble the pieces into a real login. A robust modern design splits the credential in two: a short-lived access credential used on every request, and a longer-lived refresh credential used only to mint new access credentials.

Why split them? Because it lets you have your cake and eat it. The access credential is used constantly, so you want it short-lived — if it leaks, it's useless in minutes. But you don't want to force the user to re-enter their password every fifteen minutes, so the refresh credential — used rarely, guarded tightly (ideally an HttpOnly, SameSite cookie scoped to just the refresh endpoint) — quietly issues fresh access credentials in the background.

Browser (client)Backend1. POST /login { user, password }verify password with a KDF, mint credentials2. Set access (short) + refresh (long)3. GET /api/data (+ access credential)check credential — no password needed4. 200 OK { data }— access credential expires —5. POST /refresh (+ refresh credential)6. new access credential (silent re-auth)

Here's the same flow in pseudocode, so the logic is unambiguous:

Login and refresh, in pseudocode

POST /login  { username, password }
  record = users.find(username)
  if not verify_password(password, record.password_hash):   # KDF: bcrypt/Argon2
      return 401
  access  = issue_access(user, ttl = 15 minutes)            # short-lived
  refresh = issue_refresh(user, ttl = 14 days)              # long-lived, revocable
  set_cookie("access",  access,  HttpOnly, Secure, SameSite=Lax)
  set_cookie("refresh", refresh, HttpOnly, Secure, SameSite=Strict, Path=/refresh)
  return 200

GET /api/data (browser auto-sends the access cookie) claims = validate(access) # signature + expiry, or session lookup if invalid: return 401 # client should then call /refresh return data_for(claims.user)

POST /refresh (browser auto-sends the refresh cookie) if not valid_and_not_revoked(refresh): return 401 access = issue_access(user, ttl = 15 minutes) set_cookie("access", access, HttpOnly, Secure, SameSite=Lax) return 200

Logout and revocation

Logout is where the session-vs-token split shows its teeth again. With server-side sessions, logout is a delete: drop the record and the session ID is instantly worthless everywhere. With stateless tokens, you can throw away the client's copy, but a stolen access token stays valid until it expires — the server has no per-token record to delete. That's exactly why access tokens are kept short and why the long-lived refresh token is usually made revocable (stored server-side or on a denylist). Logout then means: clear the cookies and revoke the refresh token so no new access tokens can be minted. Part 2 goes deep on making stateless tokens revocable without throwing away their statelessness.

Session vs token, side by side

The same three moments — login, an authenticated request, and a refresh — play out in both models at once. Watch the authenticated-request step in particular: the session backend does a store lookup, while the token backend does a local signature verify with no lookup at all.

Step 0 / 9

Sane Defaults for a SPA + API

If you're shipping a single-page app talking to your own backend API and you just want the boring, correct answer, here it is:

A safe starting point

  • Serve everything over HTTPS; set Secure on every auth cookie.
  • Keep the session ID / access token in an HttpOnly cookie, not localStorage — so XSS can't steal it.
  • Set SameSite=Lax (or Strict where UX allows), and add anti-CSRF tokens for state-changing requests.
  • Use short-lived access credentials (minutes) plus a longer-lived, revocable refresh credential scoped to the refresh endpoint.
  • Verify passwords with a real password-hashing KDF (Argon2id or bcrypt) — never a bare hash.
  • On logout, clear the cookies and revoke the refresh credential; don't rely on the client discarding it.
  • Reduce XSS at the source: escape output and ship a strong Content-Security-Policy. HttpOnly is a backstop, not a cure.

That checklist will carry a typical app a long way. But it leaves big questions open: what exactly is inside a signed token, and can you read it? How do you revoke something that was designed to be stateless? How do "log in with Google" delegation flows actually work without handing your password to a third party? And when is a JWT the wrong tool entirely?

Those are the subject of the follow-up, Hardening Web Auth — where we crack a JWT open, walk the OAuth authorization-code + PKCE flow end to end, and look at what happens when short-lived-and-stateless isn't enough.


Web authentication is, at heart, a story about a stateless protocol and a small carried token that stands in for you. Get the token's home right — an HttpOnly, Secure, SameSite cookie for most apps — and you've closed off the two attacks that steal credentials outright. Everything else is refinement on top of that foundation.