17. Hardening Web Auth
JWT internals, OAuth/OIDC, revocation, and token binding
Web Authentication left us with a clean picture: HTTP
forgets you, so login trades a password for a carried token, and the safest home
for that token in a browser is an HttpOnly, Secure, SameSite cookie. We
sketched the stateless-token model but treated the token itself as a black box —
"a signed blob the server can verify."
Now we open the box. This article is about what's actually inside modern tokens,
why a self-contained token is so hard to revoke, how "log in with Google"
delegation really works, and the sharp edges — alg:none, algorithm confusion,
replay — that have burned real systems. Everything here builds on
digital signatures and
hashing from earlier in the series.
Cracking Open a JWT
A JWT is the most common stateless bearer token. It looks like an opaque smear of characters, but it has a rigid three-part structure, separated by dots:
Each of the first two parts is a JSON object, base64url-encoded. Base64url is encoding, not encryption — it's trivially reversible. Anyone who intercepts the token can paste those first two segments into a decoder and read every claim. Say that out loud, because it's the most common JWT misconception:
A JWT is signed, not encrypted
The header and payload are in plain sight — base64url is just reversible encoding. What the signature buys you is integrity and authenticity: the server can detect if a single byte changed, and confirm the token came from something holding the signing key. It buys you nothing in the way of confidentiality. Never put a secret in a JWT payload.
The header and the signature
The header names the signing algorithm and, in production, a key identifier:
Decoded header and payload
// header — base64url of:
{ "alg": "RS256", "typ": "JWT", "kid": "2026-07-a" }
// payload — base64url of:
{
"iss": "https://auth.example.com", // issuer — who minted this
"sub": "alice", // subject — who it is about
"aud": "https://api.example.com", // audience — who it is FOR
"iat": 1720224000, // issued-at — when
"nbf": 1720224000, // not-before — earliest valid time
"exp": 1720224900 // expiry — 15 minutes later
}
The signature covers base64url(header) + "." + base64url(payload). Flip any bit
in the header or payload and the signature no longer verifies. That is the whole
tamper-evidence mechanism. The claims are standardized "registered claims" from
RFC 7519, and a correct verifier checks the temporal ones (exp, nbf) and
the contextual ones — crucially aud (is this token meant for this API?) and
iss (did it come from an issuer I trust?). Skipping aud/iss is a classic
foot-gun: a token minted for one service gets happily replayed against another.
HS256 vs RS256/EdDSA
The alg header picks the signature scheme, and the two families behave very
differently:
HS256 — symmetric (HMAC-SHA256)
One shared secret both signs and verifies. Fast and simple, but everyone who can verify can also forge. Fine within a single service that holds the secret; a problem the moment a second party needs to verify tokens.
RS256 / EdDSA — asymmetric
A private key signs; a freely-published public key verifies. Any number of services can verify without being able to mint tokens. This is the asymmetric split from the signatures article, applied to tokens. EdDSA (Ed25519) is the modern default; RS256 remains ubiquitous.
The alg foot-guns
Because the token itself declares which algorithm to use, a naive verifier can be tricked into using the wrong one. Two historic attacks:
-
alg: "none"The JWT spec includes an "unsecured" mode where
algisnoneand the signature is empty. An attacker rewrites the payload (say,"sub": "admin"), setsalgtonone, and drops the signature. A verifier that trusts the token's ownalgsees "no signature required" and accepts it. Defense: never acceptnone; pin the expected algorithm server-side. -
RS256 → HS256 confusion
The server expects RS256 and holds a public key to verify. An attacker changes
algtoHS256and signs the forged token using that public key as if it were the HMAC secret. A verifier that picks the algorithm from the header will HMAC-verify with the public key — which the attacker also has — and the forgery passes. Defense (again): the server, not the token, decides the algorithm.
The unifying lesson
Both attacks come from letting attacker-controlled data (the alg
header) choose how the token is validated. A hardened verifier fixes the
acceptable algorithm(s) in its own configuration and refuses anything else.
Keep this in mind — it's exactly the design flaw PASETO sets out to eliminate.
JWT inspector
Everything here runs client-side — no network. Paste any JWT (or use the samples). The header and payload are just base64url, reversible encoding rather than encryption, so they decode to plain JSON right in your browser. The signature is checked with SubtleCrypto against the shared secret; edit the payload and watch it break live.
The Stateless / Revocable Tension
Here's the bill for statelessness. A server-side session can be killed instantly:
delete the record. A signed JWT has no server-side record to delete — it is valid
precisely because the signature checks out, and it will keep checking out until
exp passes, no matter how badly you want it dead. Password change, account
compromise, "log out everywhere" — none of them reach an access token already in
the wild.
There's no way to make a purely stateless token instantly revocable and keep it purely stateless; you buy revocability back with a bit of server state. The three practical strategies, in increasing weight:
The pragmatic sweet spot most systems land on is the middle option: short-lived access tokens plus a revocable refresh token. You keep the fast, lookup-free verification on the hot path (every API call) and pay for state only on the rare refresh. That's the same access/refresh split from Part 1, now justified by revocation, not just convenience.
OAuth 2.0 and OIDC: Delegation Done Right
So far one backend authenticates its own users. But how does "Log in with Google" work — letting a third-party app act on your behalf without ever seeing your password? That's delegation, and it's the problem OAuth 2.0 solves.
The insight: instead of giving an app your password (which would let it do anything, forever), you send the app to the identity provider, log in there, and the provider hands the app a scoped, expiring access token. The app never touches your credentials.
Two specs work together:
OAuth 2.0 — authorization
About access: it issues an access token that lets an app call an API on your behalf, limited to specific scopes ("read your calendar" but not "send email").
OIDC — authentication
OpenID Connect is a thin layer on top of OAuth that adds an ID token (always a JWT) describing who you are. OAuth answers "what can this app do"; OIDC answers "who logged in."
Authorization Code + PKCE, one worked flow
The modern, recommended flow for browser and mobile apps is authorization code with PKCE (pronounced "pixy," RFC 7636). PKCE stops an attacker who intercepts the authorization code from redeeming it, by binding the redemption to a secret only the real client knows.
The trick is in steps 1 and 3. The client invents a random code_verifier, hashes
it to a code_challenge, and sends only the challenge with the authorization
request. Later it redeems the code by presenting the original verifier. The
server hashes it and checks it matches the challenge it saw earlier. An attacker
who steals the authorization code off a redirect can't redeem it — they never had
the verifier, and can't reverse the SHA-256 hash to find it. Three token types
come out the far end:
- Access token — call APIs on the user's behalf (scoped, short-lived).
- ID token — a JWT proving who logged in (OIDC; for the client, not the API).
- Refresh token — mint fresh access tokens without sending the user back to log in.
PASETO: Removing the Foot-guns
Every JWT pitfall above traces back to one design choice: algorithm agility. JWT lets the token declare its own algorithm from a menu, and expects every implementer to validate that choice perfectly. PASETO (Platform-Agnostic Security Tokens) takes the opposite stance — versioned protocols instead of algorithm agility.
JWT — algorithm agility
The token names its algorithm (alg). Flexible, but it invites
alg:none and RS256→HS256 confusion, downgrade attacks, and
a long history of library mistakes. Every verifier has to get the algorithm
handling exactly right.
PASETO — versioned protocols
You pick a version, and the algorithms come fixed and vetted. There
is no algorithm field to attack: v4.public is
always Ed25519; v4.local is
always XChaCha20 authenticated encryption. No
none, no confusion, no downgrade.
The local vs public split maps neatly onto symmetric vs asymmetric: local
tokens are encrypted (confidential, shared-secret) and public tokens are
signed (readable, publicly verifiable). A v4.local PASETO fixes the other JWT
gotcha too — unlike a default JWT, its payload really is encrypted. The tradeoff
is ecosystem size: JWT is everywhere (every OAuth/OIDC provider speaks it), while
PASETO trades that ubiquity for a smaller-but-safer design. If you control both
ends and want fewer sharp edges, PASETO is a strong choice; if you're
interoperating with the wider OAuth world, you'll be speaking JWT.
Sender-Constraining: Stop Replay at the Root
Every token discussed so far is a bearer token: whoever holds it can use it. If one leaks — via a proxy log, an XSS bug, a misconfigured redirect — the thief can replay it anywhere until it expires. Sender-constrained (proof-of-possession) tokens close that door by binding the token to a key the legitimate client holds, so a stolen token alone is useless.
-
DPoP (RFC 9449)
The client generates a key pair and, on each request, sends a small signed "DPoP proof" JWT alongside the access token. The token is bound to the client's public key; the server checks the request is signed by the matching private key. A stolen access token without the private key can't be replayed. Application-layer, works over plain HTTPS.
-
mTLS-bound tokens
Bind the token to the client's TLS client certificate (mutual TLS). The token is only accepted on a connection using that same certificate. Stronger, but needs client-cert infrastructure. Transport-layer rather than application-layer.
Both turn "possession is proof" into "possession plus a private key is proof." Combined with short expiry, they shrink the value of a stolen token to nearly nothing — a solid replay defense for high-value APIs.
Key Rotation: kid and JWKS
Asymmetric tokens (RS256/EdDSA) depend on the verifier having the right public key — and you must be able to rotate signing keys without a flag-day where every old token breaks. Two mechanisms make rotation smooth:
Rotation then works cleanly: publish the new key to the JWKS, start signing new
tokens with the new kid, keep the old key around until the last token signed
with it has expired, then drop it. A caution worth stating: because the verifier
trusts kid to select a key, treat it like any other untrusted input — look it up
against your known key set, never use it to fetch a key from an attacker-supplied
URL.
Hardening checklist
- Pin the algorithm server-side. Never trust the token's
alg; rejectnoneand unexpected algorithms — this killsalg:noneand RS256→HS256 confusion. - Validate every claim that matters:
exp,nbf, and especiallyaudandiss— a token for one service must not work on another. - Remember a JWT is readable. Base64url is encoding, not encryption — never put secrets in the payload.
- Keep access tokens short-lived and pair them with a revocable refresh token; add a
jtidenylist if you need instant revocation. - Use authorization-code + PKCE for browser and mobile apps; validate
redirect_uriandstate. - Rotate keys with
kid+ JWKS; validatekidagainst your known key set only. - For high-value APIs, consider sender-constrained tokens (DPoP or mTLS) to defeat replay of stolen tokens.
- Prefer asymmetric (EdDSA/RS256) when more than one service verifies; consider PASETO if you control both ends and want fewer foot-guns.
Stateless tokens are a bargain with a price tag. They hand you effortless horizontal scaling and lookup-free verification, and in return they ask you to be disciplined: fix the algorithm, check the claims, keep expiries short, plan for revocation and rotation from day one. Do that — and lean on the delegation and sender-constraining machinery when the stakes rise — and the humble carried token from Part 1 becomes something you can actually trust at scale.