JSON Web Token (JWT) — Auth

A JWT = header.payload.signature, each base64url. The header and payload are readable by anyone, so no secrets in them. The signature = HMAC-SHA256 of…

With a session, the server looks the session ID up in its store on every request. What if the server didn't have to look anything up?

That's the idea behind a JWT (JSON Web Token, standard RFC 7519): a token the server signs and the client then carries on every request. The server only checks the signature, then reads the content. Think of a concert ticket with a hologram: your name, your seat and the hours it's valid are printed on it. The gate staff don't phone the office, they just check the hologram is real and the time hasn't passed. But remember, anyone holding the ticket can read what's printed on it.

Three parts, separated by dots

This is the token School Portal gives Siti when she logs in at 07:00, living 15 minutes. The Lab makes exactly the same token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwibmFtZSI6IlNpdGkiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MTUwNDAwMCwiZXhwIjoxNzkxNTA0OTAwfQ.dw3HXqJYdazV7geFSKXZj28C4SLbAOdHoHpKE8meJOQ
Part What it holds
Header {"alg":"HS256","typ":"JWT"}
Payload {"sub":"1","name":"Siti","role":"student","iat":1791504000,"exp":1791504900}
Signature 32 bytes of HMAC-SHA256 over header.payload, with the server's secret

The payload's entries are called claims. The standard ones: sub (subject, who it belongs to, here the user id), iat (issued at, when it was made) and exp (expiration, when it ends). iss (the issuer) and jti (a unique token id) are common too. name and role are School Portal's own claims. Times are written as Unix time: the number of seconds since 1 January 1970 UTC. 1791504000 is 9 October 2026 at 07:00 school time (UTC+7), and exp is 900 seconds later, at 07:15.

Base64url: anyone can read the payload

The header and the payload are just JSON encoded as base64url: Base64 with + and / replaced by - and _, and no = at the end, so it's safe in a URL. That's an encoding, not encryption. Anyone can read it without a key:

function decodeJWT(token) {
  const payload = token.split(".")[1]; // the second part
  const base64 = payload.replace(/-/g, "+").replace(/_/g, "/"); // back to plain Base64
  return JSON.parse(atob(base64));
}

const sitiToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwibmFtZSI6IlNpdGkiLCJyb2xlIjoic3R1ZGVudCIsImlhdCI6MTc5MTUwNDAwMCwiZXhwIjoxNzkxNTA0OTAwfQ.dw3HXqJYdazV7geFSKXZj28C4SLbAOdHoHpKE8meJOQ";
console.log(decodeJWT(sitiToken).role); // "student"

So never put a password, an ID card number or any secret in the payload.

atob is right only for ASCII text: the name José comes out as José, so for such text use new TextDecoder().decode(Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))).

Signature: proof from the server

The signature is the HMAC-SHA256 of the text header.payload with a secret only the server knows. Change one letter of the payload and the signature no longer matches. Making one with Web Crypto:

const enc = new TextEncoder();
const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");

async function signJWT(payload, secret) {
  const header = b64url(enc.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
  const body = b64url(enc.encode(JSON.stringify(payload)));
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const sig = await crypto.subtle.sign("HMAC", key, enc.encode(header + "." + body));
  return header + "." + body + "." + b64url(new Uint8Array(sig));
}

When a request arrives with Authorization: Bearer <token>, the server checks in order, and stops at the first check that fails with 401:

  1. The token has three parts.
  2. alg equals the algorithm the server uses, HS256. The server decides, not the token's header.
  3. The server computes the HMAC of header.payload again with its secret (crypto.subtle.verify), and it must equal the signature in the token.
  4. exp is still in the future.

Only once all four pass may sub and role be trusted. Why this order and each check matter, from the attack side, is in the JWT Security lesson of the Security track. One consequence you should know as the builder: changing the secret (rotation) makes every old token fail at step 3, so everyone must log in again.

If one issuer makes tokens for more than one app, for example the Portal and MyCanteen (the school canteen app), add a fifth check: iss (the issuer) and aud (audience, which app the token is for) must equal what the Portal expects, for example https://portal.school.test and portal (RFC 8725). Without this check, a token for MyCanteen made with the same key is accepted by the Portal too.

The secret must be random, at least 32 bytes (256 bits, RFC 7518), for example from openssl rand -base64 32. A word such as portal123 can be guessed from a single token, on the attacker's own computer (RFC 8725). Other options for the algorithm:

Algorithm When to pick it
HS256 (this lesson) the same server makes and checks the tokens. One secret, the simplest.
ES256 or Ed25519 another server, for example MyCanteen, also checks them. The token maker holds the private key, a checker needs only the public key. With HS256, a checker holds the same secret, so it can also make a role: "admin" token that the Portal accepts.

exp is seconds, not milliseconds

exp and iat are in seconds. Date.now() in JavaScript is in milliseconds. Make the units match first:

function isExpired(payload) {
  return payload.exp * 1000 <= Date.now(); // at the exp second itself, it counts as over
}

Siti's token payload holds "exp": 1791504900, and at the moment of the check Date.now() is 1791504600000. Before you look at the table, guess: has the token expired or not?

Value
payload.exp * 1000 1791504900000 (07:15)
Date.now() 1791504600000 (07:10)
isExpired gives false, 300,000 ms left, that is 5 minutes

So Siti's token has not expired yet, there are 5 minutes left. Without * 1000, the code compares 1791504900 with 1791504600000 and thinks every token died long ago.

In PHP, time() is already in seconds. A token valid for one hour: 'exp' => time() + 3600, because 60 minutes × 60 seconds = 3,600.

Where does the client keep the token?

The client sends the token in the Authorization: Bearer <token> header. There are three places to keep it:

The details are in the Secure Storage in the Browser lesson. Whatever you pick, keep the token's life short, 15 minutes say, then extend it with a refresh token (the next lesson).

JWT or session?

Session JWT
Login data In the server's store In the token the client carries
Many servers Needs a shared store The same secret is enough
Logging out or revoking access Delete the entry, effective at once The token stays valid until exp, unless the server keeps a list of revoked tokens

⚠️ Why does the token leak, or die too early?

TL;DR: A JWT = header.payload.signature, each base64url. The header and payload are readable by anyone, so no secrets in them. The signature = HMAC-SHA256 of header.payload with the server's secret. The server checks: three parts, the alg it decides itself, the signature, then exp, and answers 401 at the first check that fails. exp and iat are in seconds: payload.exp * 1000 <= Date.now() means expired, and one hour = time() + 3600. Send it in Authorization: Bearer, keep it short-lived, and keep it out of localStorage when you can.

⚡ Three parts, separated by dots

Meaning: A JWT = header.payload.signature. The header and the payload are JSON encoded as base64url. The signature is the HMAC-SHA256 of header.payload with a secret only the server knows.

⚡ Anyone can read the payload

Write:

function decodeJWT(token) {
  const payload = token.split(".")[1]; // the second part
  const base64 = payload.replace(/-/g, "+").replace(/_/g, "/"); // back to plain Base64
  return JSON.parse(atob(base64));
}

Meaning: Base64url is an encoding, not encryption, so the payload reads without a key. Never put a password or any secret in it.

⚡ exp is seconds, not milliseconds

Write:

function isExpired(payload) {
  return payload.exp * 1000 <= Date.now(); // at the exp second itself, it counts as over
}
Guess first: Siti's token payload holds "exp": 1791504900, and Date.now() is 1791504600000. Has it expired?

Not yet, there are 5 minutes left (300,000 ms). Without * 1000, the code compares 1791504900 with 1791504600000 and thinks every token died long ago.

Meaning: exp and iat are in seconds, Date.now() is in milliseconds. Make the units match first.

⚡ Decode is not verify

Meaning: Before trusting sub and role, the server checks in order: three parts, the alg it decides itself, the signature, then exp. As soon as one fails, the answer is 401.

What you will learn