Three parts joined by dots
The standard token format is the JWT (JSON Web Token). It is three chunks of text joined by dots:
header.payload.signature
- header: JSON naming the signing algorithm, like
{"alg":"HS256","typ":"JWT"}. - payload: JSON with the claims, the facts the token asserts:
sub(subject, the user id),name,exp(expiry timestamp). - signature: proof the server issued it (next section).
Header and payload are encoded with base64url: a way to write any bytes using only URL-safe characters. Encoding is NOT encryption. It is a reversible re-spelling, and anyone can decode it. Run the example and decode a payload yourself.
Code exercise · javascript
Run this. Buffer.from(...).toString("base64url") encodes, and decoding needs no secret at all, proving the payload is readable by anyone who holds the token.
The signature is the whole point
If anyone can decode the payload, anyone can also build a payload claiming to be user 1. What stops them is the third part.
The signature is an HMAC: a hash of header.payload mixed with a secret key only the server knows.
signature = HMAC_SHA256(header + "." + payload, secret)
When a token comes back with a request, the server recomputes the HMAC over the first two parts and compares it to the third:
- Payload tampered with? The recomputed value no longer matches. Rejected.
- Signature forged without the secret? Cannot produce a matching value. Rejected.
So the server trusts the claims without any database lookup, which is exactly the token lane from lesson 7-2. Now implement verify, it is the same HMAC call that sign uses.
Code exercise · javascript
Your turn. sign is written for you. Implement verify(token, secret): split the token on ".", recompute the HMAC over header + "." + payload, and return whether it equals the signature part. All three checks at the bottom must come out right.
Quiz
Your JWT payload is { sub: "42", role: "user" }. A clever user decodes it, changes role to "admin", re-encodes it, and sends it back. What happens on the server?
Problem
A JWT's payload is readable by anyone who holds the token. Which of its three parts is the reason the claims can still be trusted? Answer with the one word.