JSON Web Tokens
A JSON Web Token (JWT, pronounced "jot") is a compact, signed string that carries claims: facts such as "this is user 42, a customer, until 10:15". Because it's signed, any server holding the key can trust it without a database lookup. JWTs are the standard format for API access tokens and for OpenID Connect ID tokens.
Anatomy of a JWT
A JWT is three base64url-encoded parts joined by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsInJvbGUiOiJjdXN0b21lciJ9.k1hSp3Kk…
└──────────── header ───────────────┘ └─────────────── payload ──────────────┘ └ signature ┘Let's build one by hand to see that there's no magic:
Registered claims
| Claim | Meaning |
|---|---|
sub |
Subject: who the token is about (a user ID) |
iss |
Issuer: who created it (https://auth.myshop.example) |
aud |
Audience: who it's meant for (shop-api) |
exp |
Expiry time (seconds since 1970) |
iat |
Issued-at time |
nbf |
Not valid before this time |
jti |
A unique token ID (useful for revocation lists) |
You can add your own claims (role, tenant), but keep tokens small: they travel with every request.
Signing algorithms
| Algorithm | Key | Use when |
|---|---|---|
| HS256 (HMAC + SHA-256) | One shared secret signs and verifies | A single backend issues and checks its own tokens |
| RS256 (RSA), ES256 (ECDSA), EdDSA | Private key signs, public key verifies | Many services verify tokens from one identity provider; they get the public keys from a JWKS URL |
Verifying properly with a library
Never hand-roll verification in real code. Use a maintained library (jsonwebtoken or jose in Node, PyJWT in Python, Nimbus/Spring Security in Java) and check everything: signature, algorithm, expiry, issuer and audience:
Classic JWT attacks
The alg: none attack
The JWT standard includes an unsigned algorithm, none. A naive verifier that trusts the header's alg accepts a token anyone can create:
Always pass an explicit algorithms list. A related attack is algorithm confusion: tricking a server that expects RS256 into verifying an HS256 token using the public key as the HMAC secret. Fixing the allowed algorithms prevents that too.
Weak secrets
An HS256 token can be cracked offline: an attacker who has one token can try millions of candidate secrets until the signature matches. Use at least 32 random bytes (crypto.randomBytes(32).toString('base64url')), never "secret" or the app name.
The revocation problem: short tokens + refresh tokens
A JWT stays valid until it expires, even after the user logs out, changes their password or gets banned, because the server doesn't look anything up. The standard solution:
| Token | Lifetime | Stored | Used for |
|---|---|---|---|
| Access token (JWT) | Short: 5–15 minutes | Memory | Calling APIs (Authorization: Bearer …) |
| Refresh token (random, opaque) | Long: days or weeks | Server-side database + an HttpOnly cookie or secure app storage |
Getting a new access token |
When the access token expires, the client calls POST /auth/refresh with the refresh token. The server checks it in its database, so revocation works: delete the refresh token and the user is logged out within minutes. Refresh token rotation issues a new refresh token each time and invalidates the old one; if an old one is ever used again, it was probably stolen, so revoke the whole family.
(Refresh tokens are stored hashed, like passwords, so a database leak doesn't hand them out.)
Where to keep tokens in a browser
- Not
localStoragefor anything important: any XSS on your site can read it. - Access token in memory (a JavaScript variable) and refresh token in an
HttpOnly; Secure; SameSitecookie is a common, solid pattern. - Or skip tokens in the browser entirely: the Backend-for-Frontend (BFF) pattern keeps tokens on your server and gives the browser an ordinary session cookie.
When not to use JWTs
For a classic website with one backend, plain server-side sessions are simpler and easier to revoke. JWTs earn their complexity when several services must verify identity independently, or when a third-party identity provider issues them (next lesson).
Practice
- Decode a token from the second example without verifying it (
jwt.decode) and print itsexpas a date. - Add a
jtito tokens and arevokedSet; make verification fail for revoked IDs. - Explain why the refresh tokens above are stored hashed but the JWT secret isn't.
1.What does the signature of a JWT guarantee?
2.How do you prevent the "alg: none" attack?
3.Why are access tokens kept short-lived?