Rina logs in to your app and gets a token (a sign that she logged in). Out of curiosity she opens it, and it's readable: there's "role": "user" in there. If she changes that to "role": "admin" and sends the token again, will the server believe it? Hold on to your guess.
A token like Rina's is called a JWT (JSON Web Token): a login token in text form that carries the user's data and a signature from the server. Picture an official letter from the town office. Anyone holding it can read it, but only that office can make its stamp. Change one word in the letter and the stamp no longer matches the text, so the letter is rejected. In a JWT, the letter's text is the payload, and the stamp mark on the letter is the signature. The stamp tool that makes the mark is the secret: a secret key that only the server keeps. Here the word payload means the content part of the token, not a harmful input sent by an attacker.
The three parts of a JWT
A JWT has three parts separated by dots: the header, the payload and the signature. Here the header is the first part of the token, not an HTTP header. This is Rina's token from the Lab, exactly:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJSaW5hIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3NjcyMjU2MDAsImV4cCI6MTc2NzIyNjUwMH0.ctar5r1m2MZbZEFi6gdjLTyKDInvOPTFZlGknQ0YieU
The table below shows what each part holds once it is decoded, which means turned from that run of letters back into its original text:
| Part | What it holds once decoded | What it's for |
|---|---|---|
| Header (first) | {"alg":"HS256","typ":"JWT"} |
the signing algorithm and the token type |
| Payload (second) | {"sub":"42","name":"Rina","role":"user","iat":1767225600,"exp":1767226500} |
the data, called claims |
| Signature (third) | ctar5r1m2MZbZEFi6gdjLTyKDInvOPTFZlGknQ0YieU |
proof that the header and payload weren't changed |
Common claims: sub (subject, the user's id), iat (issued at, when the token was made), and exp (expiration, when the token expires). Times are Unix timestamps, the number of seconds since 1 January 1970. In this token iat 1767225600 is 1 January 2026 at 00:00 UTC, and exp is 900 seconds later, so the token is valid for 15 minutes.
Anyone can read the payload
The header and payload are only encoded with base64url. Base64 is a way to write any data with letters, digits and a few signs. base64url is base64 that uses - and _ in place of + and /, so it's safe inside a URL. Encoding only changes the form of the text; it isn't encryption. So you need no secret to read it. The code below reads what is inside Rina's token:
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJSaW5hIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3NjcyMjU2MDAsImV4cCI6MTc2NzIyNjUwMH0.ctar5r1m2MZbZEFi6gdjLTyKDInvOPTFZlGknQ0YieU";
function decodePart(part) {
const b64 = part.replace(/-/g, "+").replace(/_/g, "/"); // base64url back to plain base64
const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
return JSON.parse(new TextDecoder().decode(bytes));
}
const [header, payload] = token.split(".");
console.log(decodePart(header)); // { alg: "HS256", typ: "JWT" }
console.log(decodePart(payload)); // { sub: "42", name: "Rina", role: "user", iat: 1767225600, exp: 1767226500 }
token.split(".")breaks the token into its three parts.replaceturns-into+and_into/, thenatobreads the base64.TextDecoderturns the bytes into UTF-8 text, andJSON.parseturns that text into an object.
So never put passwords, ID numbers or any other secret data in the payload. The signature guarantees the data wasn't changed, but it doesn't keep it secret.
The signature: a stamp that changes with the text
With alg HS256, the server makes the signature like this: HMAC-SHA256 of the text header.payload, using the secret. HMAC is a way to compute a "fingerprint" of a text with a key. If a single letter of the text changes, the fingerprint changes completely. Without the same key, nobody can compute the right fingerprint.
When Rina swaps "user" for "admin", the payload changes but the signature is still the old one, ctar5r1m.... The server recomputes the signature from the new payload and gets WjEImYyq.... They differ, so the server rejects it with a 401. That's the answer to the guess. Rina can't make a new signature because she doesn't have the secret.
A correct verifier
A verifier is the server code that checks a token before trusting what's in it. This is the version the Lab uses. It uses the Web Crypto API, the cryptography tools built into browsers and Node:
const enc = new TextEncoder();
const bytesOf = (part) => Uint8Array.from(atob(part.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const jsonOf = (part) => JSON.parse(new TextDecoder().decode(bytesOf(part)));
async function verifyJwt(token, secret, now) {
if (enc.encode(secret).length < 32) throw new Error("JWT secret too short, at least 32 bytes");
const [h, p, s] = token.split(".");
const header = jsonOf(h);
if (header.alg !== "HS256") return { ok: false, error: `alg ${header.alg} is not allowed` };
const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
const valid = await crypto.subtle.verify("HMAC", key, bytesOf(s), enc.encode(`${h}.${p}`));
if (!valid) return { ok: false, error: "signature does not match" };
const payload = jsonOf(p);
if (typeof payload.exp !== "number" || now >= payload.exp) return { ok: false, error: "token expired" };
return { ok: true, payload };
}
- Check the secret's length first: if the secret is shorter than 32 bytes, the code stops with an error.
header.alg !== "HS256": the server decides the algorithm; it isn't read from the token. Only HS256 is accepted.crypto.subtle.verifyrecomputes the signature fromh.p(the header and payload joined with a dot), then compares it safely withs, the signature that was sent.now >= payload.exp: a token must not be used at or after itsexptime. A token with noexpis rejected too.
In Node, the jsonwebtoken library does the same with jwt.verify(token, secret, { algorithms: ["HS256"] }). The library doesn't require the algorithms option, but always fill it in, so the server picks the algorithm.
Two classic traps: alg none and a weak secret
{"alg":"none","typ":"JWT"}: the JWT spec knowsalg: none, meaning a token with no signature (its third part is empty). A verifier that reads the algorithm from the header will "check" with the none algorithm. That means it checks nothing, and accepts a forged payload. The verifier above rejects it because only HS256 is allowed.- A weak secret: a secret like
"secret123"(9 bytes) can be guessed by trying a list of words one by one. Whoever knows the secret can make any token they like. Use 32 random bytes, for examplecrypto.randomBytes(32).toString("hex")in Node (the result is 64 hex characters: digits and the letters a to f). Keep that secret in an environment variable (a server setting kept outside the code), and never put it in the code.
⚠️ Misreading what a JWT protects
- Secret data in the payload. Anyone holding the token can read it with
atob. - A token with no
exp, or anexpdays away. A leaked token works for that long. Use a short-lived access token (the token sent with every request), for example 15 minutes. To ask for a new access token, use a refresh token, a second token made only for that. - Thinking logout revokes the token. The server keeps no list of tokens, so the token stays valid until
exp, even after the user logs out. If you need to revoke a token at once, use a list of blocked tokens (a denylist) or a regular session. - Keeping the token in
localStorage.localStorageis storage in the browser that JavaScript can read, so an XSS script can read the token. Keep it in anHttpOnlycookie when you can.
TL;DR: A JWT (JSON Web Token) is a login token shaped header.payload.signature. The first part is the header (alg, typ), the second the payload (the token's content, claims such as sub, iat, exp), and the third the signature (the server's signature). The header and payload are only encoded with base64url, not encrypted, so anyone can read them: put no secret data in them. An HS256 signature is HMAC-SHA256 (a fingerprint of a text, computed with a key) of header.payload with the secret, the server's secret key. So a changed payload no longer matches its signature, and the server rejects it. A correct verifier (the server code that checks tokens) picks the algorithm itself: only HS256, so alg: none (a token with no signature) is rejected. The verifier also checks the signature, and rejects a token at or after its exp (expiry time). The secret should be at least 32 random bytes, and access tokens (the tokens sent with every request) should be short-lived.
⚡ Three parts, split by dots
Meaning: A JWT (JSON Web Token) is a login token shaped header.payload.signature. The header holds alg (the signing algorithm) and typ (the token type). The payload holds data called claims, such as sub (the user's id), iat (when the token was made), and exp (when the token expires). The signature proves the header and payload were not changed.
⚡ Anyone can read the payload
Write:
const [header, payload] = token.split(".");
console.log(decodePart(payload)); // { sub: "42", name: "Rina", role: "user", iat: 1767225600, exp: 1767226500 }
Meaning: token.split(".") breaks the token at its dots, then decodePart turns the payload back into data. The header and payload are only encoded with base64url (rewritten with letters and digits), not encrypted, so you need no key at all to read them. Never put passwords or any other secret data in the payload.
⚡ A stamp that changes with the text
Guess first: in the payload of that token, Rina swaps "user" for "admin" and sends the token again. Does the server believe it?
No. The server recomputes the signature from the new payload. It differs from the old signature, so the token is rejected with a 401. Rina doesn't have the secret (the server's secret key) to make a new signature.
Meaning: An HS256 signature is HMAC-SHA256 of header.payload with a secret only the server keeps: a fingerprint of the text computed with that key. Like the stamp on an official letter, only the holder of the secret can make it.
⚡ The server picks the algorithm
Write:
if (header.alg !== "HS256") return { ok: false, error: `alg ${header.alg} is not allowed` };
Meaning: This line rejects a token whose alg is not HS256. alg: none means a token with no signature, so it isn't safe. A correct verifier (the server code that checks tokens) only accepts HS256, rejects a token at or after its exp, and its secret is at least 32 random bytes.