These are the notes for Cybersecurity Fundamentals (defensive), episode 31. In episode 30 one judge (the PDP) decided who may do what. Today's question: when Ravi's app becomes twenty small services, how does each one know who's calling, without asking the login server on every request? We invent the token, build a JWT (JSON Web Token) by hand, break it four different ways and fix each one: bearer tokens, opaque vs self-contained tokens, Base64url, the JWT's header, payload and signature, JWS and JWE, the registered claims (iss, sub, aud, exp, nbf, iat, jti), HS256 vs RS256 vs ES256, kid and JWKS, alg=none and algorithm confusion, token expiry, revocation, refresh tokens and refresh-token rotation, and where a browser should keep a token (cookie vs localStorage). Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Ravi, Neha, Kabir, user-1042, every key, secret and URL here are made up, and everything runs locally on toy data. Every code sample runs with Python 3.13 (standard library only); outputs are real, copied from actual runs. The attack demos are tiny toy verifiers we write ourselves, shown next to the fixed version: never test tokens against systems you don't own.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| Twenty services all ask one session database | Bearer token, opaque vs self-contained token |
| Kabir edits his own token from "staff" to "admin" | Base64url is encoding, not protection |
| Make the token tamper-proof | Signature, JWT = header.payload.signature, HS256 (HMAC-SHA256) |
| Anyone can read the payload | JWS (signed) vs JWE (encrypted) |
| A stolen week-old token; a token sent to the wrong service | Claims: iss, sub, aud, exp, nbf, iat, jti |
| One shared secret copied into 20 services | Asymmetric signatures: RS256, ES256 |
| Changing keys safely | kid (key ID), JWKS, key rotation |
| The token chooses how it's checked | alg=none, algorithm confusion, pinning the algorithm |
| A token you can't take back | Revocation, short expiry, refresh tokens, rotation, reuse detection |
| Scripts on the page can read the token | localStorage vs HttpOnly cookies, XSS and CSRF |
Problem 1: twenty services, one session table
In episode 28, after login the server gave the browser a session ID: a random key into the server's own session table. That works for one server. Now Ravi's shopping app is split into twenty services (orders, payments, search ...). If every request makes every service ask the same session database, that database becomes a bottleneck (a single narrow point everything waits on), and if it goes down, all twenty stop.
Coat-check tag or boarding pass?
| Real life | Token idea | Meaning |
|---|---|---|
| A cash note: whoever holds it can spend it | Bearer token | Whoever holds (bears) the token can use it; no other proof. So it must never leak. |
| A coat-check tag "No. 47" | Opaque token | A random string that means nothing by itself; the server looks it up (our session ID). |
| A boarding pass with name, flight and seat printed | Self-contained token | Carries the facts itself; a service can read and check it without a database lookup. |
A token is a small piece of data that proves something about you. Opaque tokens are easy to cancel (delete the row) but need a lookup; self-contained tokens need no lookup but are hard to cancel (Problem 6).
Problem 2: a token the user can edit
Demo 1: the obvious way, Base64-encoded JSON
# The obvious way: put the user's details in the token, just Base64-encoded
import base64, json
def make_token(user):
return base64.urlsafe_b64encode(json.dumps(user).encode()).decode()
def read_token(token):
return json.loads(base64.urlsafe_b64decode(token))
token = make_token({"user": "kabir", "role": "staff"})
print("token: ", token)
print("decoded:", read_token(token)) # anyone can read it
# Kabir decodes his own token, edits one word, encodes it again
forged = make_token({"user": "kabir", "role": "admin"})
print("server sees:", read_token(forged)) # ...and the server believes it
Output:
token: eyJ1c2VyIjogImthYmlyIiwgInJvbGUiOiAic3RhZmYifQ==
decoded: {'user': 'kabir', 'role': 'staff'}
server sees: {'user': 'kabir', 'role': 'admin'}
Kabir became an administrator with a text editor. Why? Base64 is an encoding, not encryption: it turns any bytes into 64 safe characters (A-Z, a-z, 0-9 and two symbols) so they survive in headers and URLs, and anyone can turn them back. Base64url is the same alphabet but with - and _ instead of + and / (and usually without the = padding), so it's safe inside URLs. Nothing in the token proves who wrote it.
The fix: a signature, the JWT
Remember HMAC from the cryptography episodes: a short code computed from a message and a secret key. Without the key you can't make it, and changing any letter of the message changes it completely. Add one and you get a JWT, a JSON Web Token, defined in RFC 7519 (May 2015): "a compact, URL-safe means of representing claims" as a JSON object that can be signed or encrypted.
header . payload . signature
{"alg":"HS256", {"sub":"kabir","role":"staff"} HMAC-SHA256(secret,
"typ":"JWT"} header + "." + payload)
-- Base64url -- -------- Base64url -------- ---- Base64url ----
- Header: which algorithm signed it (
alg), the type (typ), optionally a key ID (kid). - Payload: the facts, called claims.
- Signature: covers header and payload together.
- HS256 = HMAC with SHA-256, using one secret key that only the login server knows (a symmetric algorithm).
Demo 2: sign it, then try to forge it
# The fix: sign it. A JWT = header.payload.signature, each part Base64url-encoded
import base64, hashlib, hmac, json
def b64url(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64url(text): return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
SECRET = b"auth-server-secret-k7Q2xVp9" # known ONLY to the server
def sign(payload):
head = b64url(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
body = b64url(json.dumps(payload).encode())
sig = hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest()
return f"{head}.{body}.{b64url(sig)}"
def verify(token):
head, body, sig = token.split(".")
good = hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest()
if not hmac.compare_digest(unb64url(sig), good): return "REJECTED: bad signature"
return json.loads(unb64url(body))
token = sign({"sub": "kabir", "role": "staff"})
for part in token.split("."): print(" ", part)
print("valid: ", verify(token))
head, body, sig = token.split(".") # Kabir edits the payload again
evil = b64url(json.dumps({"sub": "kabir", "role": "admin"}).encode())
print("forged: ", verify(f"{head}.{evil}.{sig}"))
Output:
eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9
eyJzdWIiOiAia2FiaXIiLCAicm9sZSI6ICJzdGFmZiJ9
1zX-4NGjQdtrTtZP0k3qRzHKEDHygPAiUswrZ4PKNOw
valid: {'sub': 'kabir', 'role': 'staff'}
forged: REJECTED: bad signature
The edited payload no longer matches the signature. Note hmac.compare_digest: it compares in constant time (it takes the same time whether the first or the last byte differs), so an attacker can't guess a signature byte by byte from timing.
Notice that the first two parts start with eyJ: that's simply how Base64 writes {". Paste any JWT into a decoder and the payload is readable. Signed does not mean secret.
JWS vs JWE
| JWS (JSON Web Signature) | JWE (JSON Web Encryption) | |
|---|---|---|
| Protects | Integrity (nobody can change it) | Confidentiality (only the key holder can read it) |
| Anyone can read the payload? | Yes | No |
| How common | Most JWTs you'll meet | When the token itself must hide data |
| CIA triad (episode 2) | I | C |
Rule: never put passwords, card numbers, Aadhaar-style ID numbers or other secrets in a signed (JWS) payload.
Problem 3: a valid signature isn't enough (claims)
Neha's token was accidentally written into a log file last week and copied: the signature is still valid. A token issued for the orders service is replayed at payroll: same login server, same key, valid signature. A signature only proves who wrote the token; the token must also say who it's about, who it's for, and until when. Those statements are claims.
The seven registered claims (RFC 7519)
| Claim | Name | Meaning | Example |
|---|---|---|---|
iss |
Issuer | Who made the token | "https://login.ravi.example" |
sub |
Subject | Who the token is about | "user-1042" |
aud |
Audience | Who may accept it; a recipient not listed must reject it | ["orders-api"] |
exp |
Expiration time | Must not be accepted on or after this time | 1800000900 |
nbf |
Not before | Must not be accepted before this time | 1800000000 |
iat |
Issued at | When it was made (its age) | 1800000000 |
jti |
JWT ID | A unique ID for this token; helps spot replays | "a81f-77c2" |
Times are Unix timestamps: the number of seconds since 1 January 1970 (UTC). 1800000000 is a moment in January 2027.
Demo 3: signature-only vs checking claims
# Claims: the signature proves WHO wrote it, the claims say WHEN and FOR WHOM it is valid
import time
NOW = int(time.time())
def check_signature_only(claims): return "ACCEPT" # the obvious validator
def check_claims(claims, me="orders-api"):
if claims["iss"] != "https://login.ravi.example": return "REJECT: unknown issuer (iss)"
if me not in claims["aud"]: return "REJECT: not for me (aud)"
if NOW >= claims["exp"]: return "REJECT: expired (exp)"
if NOW < claims.get("nbf", 0): return "REJECT: not valid yet (nbf)"
return "ACCEPT"
base = {"iss": "https://login.ravi.example", "sub": "user-1042", "aud": ["orders-api"],
"iat": NOW - 60, "exp": NOW + 900, "jti": "a81f-77c2"}
tests = {"fresh token": base,
"stolen last week": {**base, "iat": NOW - 7*86400, "exp": NOW - 7*86400 + 900},
"meant for payroll": {**base, "aud": ["payroll-api"]}}
for name, claims in tests.items():
print(f"{name:18} sig-only: {check_signature_only(claims):7} claims: {check_claims(claims)}")
Output:
fresh token sig-only: ACCEPT claims: ACCEPT
stolen last week sig-only: ACCEPT claims: REJECT: expired (exp)
meant for payroll sig-only: ACCEPT claims: REJECT: not for me (aud)
A good validator checks the signature first, then every claim: iss exactly equals the issuer you trust, your own name is in aud, exp hasn't passed, nbf has. Keep access tokens short-lived (minutes, not days), and allow a small clock skew (also called leeway), about a minute, because server clocks drift.
Problem 4: one secret in twenty places (RS256, ES256)
HS256 is symmetric: the same secret both signs and verifies. To let twenty services verify, Ravi copies the secret into all twenty, and if any one is hacked, the attacker can mint (create) admin tokens for every service. Verifying should not mean being able to sign.
The fix is asymmetric cryptography (the earlier crypto episodes): the login server signs with a private key; every service verifies with the matching public key, which can check a signature but cannot make one.
| Algorithm | What it is | Keys | Notes |
|---|---|---|---|
| HS256 | HMAC with SHA-256 | One shared secret | Fine when the signer and the verifier are the same service |
| RS256 | RSA signature (PKCS#1 v1.5) with SHA-256 | Private signs, public verifies | Very widely supported; keys of 2048 bits or more (RFC 7518) |
| ES256 | ECDSA (Elliptic Curve Digital Signature Algorithm) on the P-256 curve with SHA-256 | Private signs, public verifies | Same idea with much smaller keys and signatures |
Demo 4: a public key can't forge (toy RSA)
This is textbook RSA on two known primes, only to see the idea. Never use it for real: real code uses a tested crypto library (in Python, for example, the cryptography package) with proper padding.
# RS256 idea with TOY textbook RSA (real code uses a crypto library, never this)
import hashlib
p, q = 2**521 - 1, 2**607 - 1 # two known primes (toy!)
n, e = p * q, 65537 # PUBLIC key: (n, e), anyone may have it
d = pow(e, -1, (p - 1) * (q - 1)) # PRIVATE key: only the login server
def h(msg): return int.from_bytes(hashlib.sha256(msg.encode()).digest(), "big")
def sign(msg, key): return pow(h(msg), key, n)
def verify(msg, sig): return pow(sig, e, n) == h(msg) # needs only the PUBLIC key
token = '{"sub": "user-1042", "role": "staff"}'
sig = sign(token, d) # the login server signs
print("orders-api verifies:", verify(token, sig))
fake = '{"sub": "user-1042", "role": "admin"}'
print("orders-api mints with the public key:", verify(fake, sign(fake, e)))
print("public key digits:", len(str(n)), "| private key digits:", len(str(d)))
Output:
orders-api verifies: True
orders-api mints with the public key: False
public key digits: 340 | private key digits: 339
Only the login server can sign, and it guards one private key, ideally inside the KMS (key management system) or HSM (hardware security module) from episode 27.
kid, JWKS and key rotation
| Passport office | Tokens |
|---|---|
| A stamp number on each visa | kid (key ID): a header field naming the key that signed the token |
| A public book of stamp samples | JWKS (JSON Web Key Set): the issuer's public keys as a JSON file at a public URL |
| A new stamp each year; the old one stays in the book until its visas expire | Key rotation: sign new tokens with a new kid, keep the old public key published until the old tokens expire |
A JWKS looks like this (shortened):
{"keys": [
{"kty": "RSA", "kid": "2026-11", "use": "sig", "alg": "RS256", "n": "0vx7agoebGcQ...", "e": "AQAB"},
{"kty": "RSA", "kid": "2026-10", "use": "sig", "alg": "RS256", "n": "xjlCRBqkOZcD...", "e": "AQAB"}]}
A service downloads it (and caches it), reads the token's kid, and picks that key. Only look up keys from your configured issuer's JWKS, never from a URL inside the token.
Problem 5: the token picks its own check
The header says which algorithm signed the token, but whoever builds the token writes the header.
alg=none: RFC 7519 defines an Unsecured JWT with"alg": "none"and an empty signature, for cases where something else already protects it. A verifier that honours it accepts anything.- Algorithm confusion: a server expecting RS256 receives a token marked HS256 and uses the key it has, the public key, as the HMAC secret. The public key is public, so anyone can compute that HMAC.
Both flaws were found in several real JWT libraries and disclosed by security researcher Tim McLean in 2015; the recommended fix was that the server fixes the expected algorithm (an allowlist) instead of trusting the token's alg header.
Demo 5: a careless toy verifier vs a pinned one
# A careless verifier lets the TOKEN choose the algorithm. Toy keys, local code only.
import hashlib, hmac
PUBLIC_KEY = b"-----BEGIN PUBLIC KEY----- MIIBIjANBg...(published for everyone)"
def rsa_ok(msg, sig): return False # stand-in: real RS256 check (see demo 4)
def verify_careless(header, msg, sig):
if header["alg"] == "none": return True # "no signature needed"
if header["alg"] == "HS256": # uses the ONE key it has... the public key
return hmac.compare_digest(sig, hmac.new(PUBLIC_KEY, msg, hashlib.sha256).digest())
return rsa_ok(msg, sig)
def verify_pinned(header, msg, sig):
if header["alg"] != "RS256": return False # the SERVER decides the algorithm
return rsa_ok(msg, sig)
msg = b'{"sub": "user-1042", "role": "admin"}' # forged payload
t1 = ({"alg": "none"}, msg, b"")
t2 = ({"alg": "HS256"}, msg, hmac.new(PUBLIC_KEY, msg, hashlib.sha256).digest())
for name, t in [("alg=none", t1), ("HS256 with public key", t2)]:
print(f"{name:22} careless: {verify_careless(*t)!s:5} pinned: {verify_pinned(*t)}")
Output:
alg=none careless: True pinned: False
HS256 with public key careless: True pinned: False
The fix:
- keep an allowlist of the exact algorithm(s) you expect, and tie each key to one algorithm;
- reject
nonealways; - use a well-maintained JWT library and pass the expected algorithm explicitly (for example
algorithms=["RS256"]), instead of writing your own parser.
Problem 6: you can't take it back
Neha's phone is stolen and her token lives 30 days. She clicks "log out everywhere", but services never ask a database (that was the point of a self-contained token), so they keep accepting it. Taking a token back before it expires is called revocation, and it's hard for self-contained tokens.
Access token + refresh token
| Access token | Refresh token | |
|---|---|---|
| Lifetime | Short: 5-15 minutes | Long: days or weeks |
| Sent to | Every API / service | Only the login (authorization) server |
| Format | Often a JWT | Usually opaque |
| Revocation | Waits for expiry (or a jti deny list) |
Login server checks its database: revoke here |
When the access token expires, the app quietly swaps the refresh token for a new access token. "Log out everywhere" = revoke the refresh tokens; within minutes every access token dies.
Refresh-token rotation: every refresh token works once; each use returns a new one. If an old one ever comes back, someone copied it, so the server revokes the whole family (every token from that login). RFC 9700 (January 2025, the OAuth 2.0 Security Best Current Practice) says: "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation." (A public client is an app that can't keep a secret, like a phone app; episode 32.)
Demo 6: rotation with reuse detection
# Short access tokens + refresh tokens with ROTATION: every refresh token works only once
import secrets
families = {} # refresh token -> {"family", "used"}
revoked = set()
def login(user):
rt = secrets.token_urlsafe(8); families[rt] = {"family": user, "used": False}
return rt
def refresh(rt):
rec = families.get(rt)
if rec is None or rec["family"] in revoked: return "401: log in again"
if rec["used"]: # an OLD token came back: someone copied it
revoked.add(rec["family"]); return "REUSE DETECTED: whole family revoked"
rec["used"] = True; new = secrets.token_urlsafe(8)
families[new] = {"family": rec["family"], "used": False}
return new
rt1 = login("neha")
rt2 = refresh(rt1); print("app refreshes: new token issued:", rt2 != rt1)
print("thief replays rt1: ", refresh(rt1)) # a stolen copy of the old token
print("app refreshes rt2: ", refresh(rt2)) # the real app must log in again too
Output (the token values are random on every run):
app refreshes: new token issued: True
thief replays rt1: REUSE DETECTED: whole family revoked
app refreshes rt2: 401: log in again
The real app is logged out too, on purpose: the server can't tell who's who, so it stops both, and Neha simply signs in again. For emergencies (a leaked admin token), services can also keep a short deny list of jti values until those tokens expire.
Problem 7: where the browser keeps the token
| Storage | Who can read it | Main risk | Defences |
|---|---|---|---|
localStorage / sessionStorage |
Every script on the page | XSS (cross-site scripting: an attacker's script running inside your page) reads and sends it away | Output encoding (episode 40), CSP (episode 41) |
| HttpOnly cookie (episode 28) | No script; the browser attaches it to requests | CSRF (cross-site request forgery: another site makes your browser send a request) | Secure, SameSite=Lax/Strict, CSRF tokens |
| In memory (a JavaScript variable) | Scripts on the page, until reload | XSS while the page is open | Short-lived access tokens |
| Server-side ("backend for frontend") | Only your server | Server compromise | Browser holds only an HttpOnly session cookie |
localStorage.setItem("token", jwt);
// ANY script on the page can do:
localStorage.getItem("token"); // one XSS bug = token stolen
Set-Cookie: rt=...; HttpOnly; Secure; SameSite=Strict; Path=/auth
A common safe design keeps long-lived tokens out of JavaScript entirely: a small server-side component (a backend for frontend) holds them, and the browser only carries an HttpOnly, Secure, SameSite cookie.
The next problem
A photo-printing website wants to read your photos from Ravi's app. Should you give it your password? Never. It should get a limited token, with your consent, that you can cancel. That's OAuth 2.0: episode 32.
The whole chain
- One session table for 20 services → bearer tokens that carry their own facts (self-contained).
- Base64 can be edited → a signature: the JWT, HS256; signed (JWS) is readable, encrypted is JWE.
- Stolen and misdirected tokens → claims:
iss,sub,aud,exp,nbf,iat,jti. - One secret in 20 places → RS256 / ES256, kid, JWKS, key rotation.
- The token picks its own algorithm → pin the algorithm, reject
none. - Can't take it back → short expiry, refresh tokens, rotation with reuse detection.
- Scripts read localStorage → HttpOnly cookies (or keep tokens server-side).
...and you just invented safe tokens.
Common mistakes (and what they print)
| Mistake | What you see | Why it's wrong | Fix |
|---|---|---|---|
| Trusting a Base64 payload | server sees: {'user': 'kabir', 'role': 'admin'} |
Encoding is not a signature | Verify the signature first |
| Checking only the signature | stolen last week sig-only: ACCEPT |
exp and aud ignored |
Check iss, aud, exp, nbf |
Letting the header choose alg |
alg=none careless: True |
The attacker writes the header | Allowlist one algorithm per key |
| 30-day access tokens | Logout doesn't stop the stolen phone | Self-contained = no lookup | Minutes + rotating refresh tokens |
| Decoding Base64url without restoring padding | binascii.Error: Incorrect padding |
JWTs strip the = padding |
Add "=" * (-len(s) % 4) before decoding |
| Splitting a malformed token without checking | ValueError: not enough values to unpack (expected 3, got 1) |
Untrusted input crashes the server (a 500, maybe failing open) | Catch errors and reject |
| Reading a claim that isn't there | KeyError: 'exp' |
A token without exp must not live forever |
Require exp; treat missing as reject |
Comparing a str with bytes in compare_digest |
TypeError: a bytes-like object is required, not 'str' |
Mixed types | Compare bytes with bytes |
| Secrets inside a JWS payload | Anyone with the token reads them | Signed ≠ encrypted | Keep secrets out, or use JWE |
Tokens in localStorage |
One XSS = stolen token | Every script can read it | HttpOnly cookie / backend for frontend |
Mini project: Ravi's tiny JWT toolkit
HS256 only, pinned algorithm, every claim checked with 60 seconds of leeway, kid-based key rotation, and safe handling of garbage input.
# Ravi's tiny JWT toolkit: HS256 only, pinned algorithm, every claim checked, kid-based key rotation
import base64, hashlib, hmac, json, time
def b64url(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64url(text): return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
KEYS = {"2026-10": b"old-secret-Qm81zz", "2026-11": b"new-secret-Lk27vx"} # kid -> key
CURRENT_KID = "2026-11"
ISSUER, LEEWAY = "https://login.ravi.example", 60 # 60 s clock skew
def issue(sub, aud, ttl=600, now=None, kid=CURRENT_KID):
now = int(now or time.time())
head = b64url(json.dumps({"alg": "HS256", "typ": "JWT", "kid": kid}).encode())
body = b64url(json.dumps({"iss": ISSUER, "sub": sub, "aud": aud, "iat": now,
"nbf": now, "exp": now + ttl}).encode())
sig = hmac.new(KEYS[kid], f"{head}.{body}".encode(), hashlib.sha256).digest()
return f"{head}.{body}.{b64url(sig)}"
def verify(token, me, now=None):
now = int(now or time.time())
try:
head_b, body_b, sig_b = token.split(".")
head = json.loads(unb64url(head_b))
except ValueError:
return "REJECT: malformed"
if head.get("alg") != "HS256": return "REJECT: algorithm not allowed"
key = KEYS.get(head.get("kid"))
if key is None: return "REJECT: unknown kid"
good = hmac.new(key, f"{head_b}.{body_b}".encode(), hashlib.sha256).digest()
if not hmac.compare_digest(unb64url(sig_b), good): return "REJECT: bad signature"
c = json.loads(unb64url(body_b))
if c["iss"] != ISSUER: return "REJECT: iss"
if me not in c["aud"]: return "REJECT: aud"
if now >= c["exp"] + LEEWAY: return "REJECT: expired"
if now < c["nbf"] - LEEWAY: return "REJECT: not yet valid"
return f"OK sub={c['sub']}"
T = 1_800_000_000
print("fresh :", verify(issue("user-1042", ["orders-api"], now=T), "orders-api", now=T + 5))
print("old kid, valid :", verify(issue("user-1042", ["orders-api"], now=T, kid="2026-10"), "orders-api", now=T + 5))
print("wrong audience :", verify(issue("user-1042", ["search-api"], now=T), "orders-api", now=T + 5))
print("expired + 30 s :", verify(issue("user-1042", ["orders-api"], now=T), "orders-api", now=T + 630))
print("expired + 2 min :", verify(issue("user-1042", ["orders-api"], now=T), "orders-api", now=T + 720))
none_tok = b64url(b'{"alg": "none"}') + "." + b64url(b'{"sub": "admin"}') + "."
print("alg=none :", verify(none_tok, "orders-api", now=T))
print("garbage :", verify("not-a-jwt", "orders-api", now=T))
Output:
fresh : OK sub=user-1042
old kid, valid : OK sub=user-1042
wrong audience : REJECT: aud
expired + 30 s : OK sub=user-1042
expired + 2 min : REJECT: expired
alg=none : REJECT: algorithm not allowed
garbage : REJECT: malformed
Ideas to extend it: add a jti deny list; require exp to be at most 15 minutes after iat; log every rejection with its reason (an audit trail).
Practice
1. Read a JWT without the key. Decode the header and payload of the token from Demo 2.
Solution
import base64, json
token = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiOiAia2FiaXIiLCAicm9sZSI6ICJzdGFmZiJ9.1zX-4NGjQdtrTtZP0k3qRzHKEDHygPAiUswrZ4PKNOw"
head, body, sig = token.split(".")
for part in (head, body):
print(json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4))))
{'alg': 'HS256', 'typ': 'JWT'}
{'sub': 'kabir', 'role': 'staff'}
No key was needed: a JWS is readable by anyone. That's why secrets never go in the payload.
2. An issuer failure. In Demo 3, add a token whose iss is https://login.evil.example.
Solution
import time
NOW = int(time.time())
def check_claims(claims, me="orders-api"):
if claims["iss"] != "https://login.ravi.example": return "REJECT: unknown issuer (iss)"
if me not in claims["aud"]: return "REJECT: not for me (aud)"
if NOW >= claims["exp"]: return "REJECT: expired (exp)"
return "ACCEPT"
base = {"iss": "https://login.ravi.example", "sub": "user-1042", "aud": ["orders-api"], "exp": NOW + 900}
print("fake issuer:", check_claims({**base, "iss": "https://login.evil.example"}))
fake issuer: REJECT: unknown issuer (iss)
3. Pin the algorithm in Demo 2. Make verify reject any token whose header alg isn't HS256, and test it with an alg=none token.
Solution
import base64, hashlib, hmac, json
def b64url(data): return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def unb64url(text): return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
SECRET = b"auth-server-secret-k7Q2xVp9"
def verify(token):
head, body, sig = token.split(".")
if json.loads(unb64url(head)).get("alg") != "HS256": return "REJECTED: algorithm not allowed"
good = hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest()
if not hmac.compare_digest(unb64url(sig), good): return "REJECTED: bad signature"
return json.loads(unb64url(body))
none_token = b64url(b'{"alg": "none"}') + "." + b64url(b'{"sub": "kabir", "role": "admin"}') + "."
print(verify(none_token))
REJECTED: algorithm not allowed
4. A jti deny list. Reject one leaked admin token by its jti until it expires.
Solution
denied_jti = {"a81f-77c2"} # admin token leaked: deny until it expires
def check(claims):
if claims["jti"] in denied_jti: return "REJECT: revoked (jti)"
return "ACCEPT"
print(check({"sub": "admin-7", "jti": "a81f-77c2"}))
print(check({"sub": "user-1042", "jti": "c3d0-1e9a"}))
REJECT: revoked (jti)
ACCEPT
Keep each entry only until that token's exp; after that the token is dead anyway, so the list stays small.
5. Which algorithm? (a) One service both issues and checks its own tokens. (b) A login server issues tokens checked by 40 services run by different teams. (c) Like (b), but tokens travel over slow mobile networks and size matters.
Solution
(a) HS256 is fine: signer and verifier are the same service, so the secret lives in one place. (b) RS256 or ES256: only the login server holds the private key; the 40 services get the public key from the JWKS. (c) ES256: smaller keys and much smaller signatures than RSA.
6. Opaque or self-contained? A bank wants every logout to take effect instantly on every service. Which token type, and what's the cost?
Solution
Opaque tokens (or very short JWTs plus a check on every request): each request looks the token up, so deleting it revokes it at once. The cost is a lookup on every request (latency and a central dependency), which caching and token introspection (episode 32) help with.
Quick quiz
A token made for search-api is sent to payments-api. The signature is valid, it was issued 2 minutes ago and expires in 13 minutes. Which claim check rejects it?
- A:
exp - B:
iat - C:
aud - D:
jti
Answer
C, aud. The audience names the services allowed to accept the token. payments-api isn't in it, so it must reject the token even though the signature and the times are fine.
Interview questions
- What is a bearer token, and why is that risky? A token that grants access to whoever holds it, with no other proof; if it leaks (logs, URLs, XSS) the thief can use it until it expires.
- Opaque vs self-contained tokens? Opaque: a random reference the server looks up (easy to revoke, needs a lookup). Self-contained (JWT): carries signed claims any service can verify locally (no lookup, hard to revoke).
- What are the three parts of a JWT? Base64url header (algorithm, type, key ID), payload (claims) and signature over both, joined by dots.
- Is a JWT encrypted? Usually not: a JWS is only signed and anyone can read it. JWE encrypts.
- Which claims must a resource server validate? Signature with a pinned algorithm, then
iss,aud,exp(andnbf), with a small leeway;jtiif replay protection is needed. - HS256 vs RS256? HS256 uses one shared secret (anyone who verifies can also sign); RS256/ES256 sign with a private key and verify with a public key, so verifiers can't forge.
- Explain the
alg=noneand algorithm confusion attacks. Libraries that trust the header'salgaccept unsigned tokens (none) or verify an HS256 token using the RSA public key as the HMAC secret. Fix: the server fixes the allowed algorithm per key. - What are
kidand JWKS for?kidnames the signing key in the header; the JWKS publishes the issuer's public keys so verifiers can pick the right one and keys can be rotated. - How do you revoke a JWT? Keep access tokens short-lived, revoke refresh tokens at the authorization server, and for emergencies keep a
jtideny list until expiry. - What is refresh-token rotation? Each refresh token is single-use and exchanged for a new one; reuse of an old one signals theft and revokes the whole token family.
- Where should a browser app store tokens? Preferably not in
localStorage(XSS-readable): use HttpOnly, Secure, SameSite cookies or keep tokens server-side (backend for frontend).
Glossary
| Term | Meaning in plain words | Example |
|---|---|---|
| Token | A small piece of data that proves something about you | A session ID, a JWT |
| Bearer token | A token that works for whoever holds it, like cash | Authorization: Bearer eyJ... |
| Opaque token | A random reference that means nothing by itself; the server looks it up | sid=9f2c... |
| Self-contained token | A token that carries its own facts, checkable without a lookup | A JWT |
| Bottleneck | One narrow point that everything waits on | One session database for 20 services |
| Encoding | Changing how data is written, with no secret involved | Base64 |
| Base64 | An encoding of bytes into 64 safe characters | eyJ1c2VyIjog... |
| Base64url | Base64 with - and _, usually without = padding, safe in URLs |
JWT parts |
| Padding | The = characters Base64 adds to make the length a multiple of 4 |
...fQ== |
| HMAC | A keyed code over a message; needs the secret to make or check | HMAC-SHA256 |
| JWT | JSON Web Token (RFC 7519): header.payload.signature | Demo 2 |
| Header | First JWT part: algorithm, type, key ID | {"alg":"HS256","typ":"JWT"} |
| Payload | Second JWT part: the claims | {"sub":"kabir"} |
| Signature | Third JWT part: proves who wrote it and that it wasn't changed | HMAC or RSA/ECDSA signature |
| Claim | A statement inside a token | "aud": ["orders-api"] |
| JWS | JSON Web Signature: a signed token, readable by anyone | Most JWTs |
| JWE | JSON Web Encryption: an encrypted token, readable only with the key | Tokens carrying private data |
iss |
Issuer: who made the token | https://login.ravi.example |
sub |
Subject: who the token is about | user-1042 |
aud |
Audience: who may accept it | orders-api |
exp |
Expiration time: reject on or after it | NOW + 900 |
nbf |
Not before: reject before it | NOW |
iat |
Issued at: when it was made | NOW - 60 |
jti |
JWT ID: a unique ID, to spot replays or deny one token | a81f-77c2 |
| Unix timestamp | Seconds since 1 January 1970 (UTC) | 1800000000 |
| Clock skew / leeway | A small allowance for servers' clocks disagreeing | 60 seconds |
| Symmetric | One key both signs and verifies | HS256 |
| Asymmetric | A private key signs, a public key verifies | RS256, ES256 |
| HS256 | HMAC with SHA-256 | One shared secret |
| RS256 | RSA signature with SHA-256 | Private/public RSA keys |
| ES256 | ECDSA on the P-256 curve with SHA-256 | Small keys and signatures |
| ECDSA | Elliptic Curve Digital Signature Algorithm | ES256 |
| Mint | Create a new, valid token | Only the login server should |
kid |
Key ID in the header, naming the signing key | "kid": "2026-11" |
| JWKS | JSON Web Key Set: public keys at a public URL | /.well-known/jwks.json |
| Key rotation | Regularly switching to a new key while old tokens expire | New kid each month |
alg=none |
An unsecured JWT with no signature | Must always be rejected |
| Algorithm confusion | Tricking a verifier into the wrong algorithm, e.g. HS256 with the public key | Demo 5 |
| Pinning the algorithm | The server decides which algorithm it accepts | algorithms=["RS256"] |
| Revocation | Taking a token back before it expires | "Log out everywhere" |
| Token expiry | The end of a token's life | exp |
| Access token | Short-lived token sent to APIs | 10 minutes |
| Refresh token | Long-lived token sent only to the login server to get new access tokens | Usually opaque |
| Refresh-token rotation | Each refresh token works once and is replaced | Demo 6 |
| Token family | All refresh tokens descended from one login | Revoked together on reuse |
| Reuse detection | Noticing an already-used refresh token come back | "REUSE DETECTED" |
| Deny list | A list of specific tokens to reject until they expire | Leaked jti values |
| localStorage | Browser storage any script on the page can read | localStorage.getItem("token") |
| HttpOnly cookie | A cookie scripts can't read (episode 28) | Set-Cookie: rt=...; HttpOnly |
| XSS | Cross-site scripting: an attacker's script runs in your page | Steals localStorage |
| CSRF | Cross-site request forgery: another site makes your browser send a request | Stopped by SameSite |
| Backend for frontend | A small server that holds tokens for a browser app | Tokens never reach JavaScript |
| Constant-time comparison | A comparison that takes the same time wherever bytes differ | hmac.compare_digest |
Summary
- A bearer token works for whoever holds it. Opaque tokens are looked up; self-contained tokens (JWTs) carry signed facts.
- Base64url is encoding, not protection. A JWT = Base64url header . payload . signature (RFC 7519, May 2015). JWS is signed and readable; JWE is encrypted.
- Always validate the signature with a pinned algorithm, then
iss,aud,exp,nbf(with a little leeway).subsays who;iatwhen;jtiwhich token. - HS256 shares one secret; RS256/ES256 sign privately and verify publicly.
kidnames the key, JWKS publishes public keys, rotate keys regularly. - Never let the token choose its algorithm:
alg=noneand algorithm confusion (disclosed by Tim McLean, 2015) are stopped by an allowlist. - Revocation is hard: use short access tokens, refresh tokens revocable at the login server, rotation with reuse detection (RFC 9700), and a
jtideny list for emergencies. - In browsers, keep tokens away from page scripts: HttpOnly, Secure, SameSite cookies or a backend for frontend, not
localStorage.
Next episode: OAuth 2.0 explained: delegated authorization, the four roles, access tokens and scopes, consent, the authorization code flow with PKCE, client credentials and device flows, redirect URI validation, the state parameter, and OAuth 2.1.
Sources: RFC 7519 "JSON Web Token (JWT)" (IETF, May 2015); RFC 7518 "JSON Web Algorithms"; RFC 9700 "Best Current Practice for OAuth 2.0 Security" (IETF, January 2025); Threatpost, "Critical Vulnerabilities Affect JSON Web Token Libraries" (2015) and Tim McLean's write-up on the Auth0 blog. Code outputs from Python 3.13. Fetched 5 Nov 2026.