lessons/jwt.md

Lesson 7 of 18

JWT: the signature is the whole point

A JWT payload is readable and editable by anyone. Only the signature, verified by the server, makes it trustworthy.

Remember: Verify the signature with a pinned algorithm, require exp, iss and aud, and never trust claims you have not verified.

A JWT has three parts: a header, a payload and a signature. The first two are only Base64URL-encoded, so anyone can read them and change them. The signature is what makes the token trustworthy, and only if the server actually verifies it.

claims = jwt.decode(token, options={"verify_signature": False})
Vulnerable: the claims are read without verifying the signature. Anyone can forge a token.
claims = jwt.decode(
token, SECRET, algorithms=["HS256"],
issuer="auth.example.com", audience="api.example.com",
options={"require": ["exp", "sub"]},
)
Fixed: signature checked, algorithm pinned on the server, issuer, audience and expiry required.

Common mistakes

  • Not verifying the signature at all.
  • Letting the token choose the algorithm (alg: none, or a public key used as an HMAC secret).
  • No exp claim, so the token never expires.
  • Trusting a role claim instead of reading the role from the database on each request.

Lifetime and revocation

Keep access tokens short (5 to 15 minutes), rotate refresh tokens, and keep a revocation list for logout and compromise.

Where the token lives matters. An httpOnly cookie cannot be read by JavaScript, so an XSS bug cannot copy it. A token in localStorage can be stolen by any script running on the page.

Questions to ask yourself

  1. Is the signature verified, and with which algorithm?
  2. Where does the role come from?
  3. How long does the token live, and how is it revoked?

Practise this