A verifier that accepts only two strong algorithms still accepts a forged role: admin token. The attacker signs it with HMAC, using the server's own public key as the HMAC secret, and needs no secret at all. A study guide for jwt.py.
base64, hashlib, hmac, json) and makes no network calls. No token on this page belongs to a real service. Every output on this page was captured from a real run on macOS 26.5.2 (Darwin 25.5.0), arm64 Apple Silicon, Python 3.15.0a8. The toy has no clock and no randomness, so every token is identical on every run: we ran demo.py twice and diffed the output, and there was no difference. The one exception is the timing table in section 6.5, which is a measurement and says so.
cd jwt-from-scratch
python3 demo.py # the four acts (section 6)
python3 oneline.py # the one line that decides the result (section 6.4)
python3 sweep.py # every experiment this page quotes (checks C1 to C10)
python3 test_jwt.py # tests that pin both forgeries
Suppose your server issues a token that says "this is alice, and she is a regular user". A week later it receives a token that says "this is alice, and she is an admin". The server has to decide whether it wrote that second token. That decision is the job of a verifier, and this toy is about four ways to write one.
A JSON Web Token (JWT) is a small signed document in three parts: a header, a payload of claims such as sub: alice (the subject, who the token is about) and role: user, and a signature over the first two. The header names the algorithm the signer used, in a field called alg. The toy builds JWTs from scratch and then writes four verifiers for them.
The toy supports two real signing algorithms. HS256 is HMAC with SHA-256: one shared secret both signs and verifies (section 2 explains HMAC). RS256 is an RSA signature over a SHA-256 hash: a private key signs, and a separate public key verifies. Because the public key can only verify, the server publishes it so anyone can check its tokens. The toy writes each part of a token in base64url, a reversible way to write bytes as text that is safe in a URL.
An attacker who wants role: admin has two classic ways to forge a token. The rest of the page is about which verifier stops which:
alg: none forgery. The attacker sets alg to "none", which tells the verifier the token is unsigned, and deletes the signature.alg to HS256 and signs the token with HMAC, using the server's RSA public key as the HMAC secret. The server publishes its public key, so the attacker has it.Here are the four verifiers, in the order a real codebase tends to acquire them. Each one is a reasonable response to the failure of the one before it. The source and the demo output number them v0 to v3, so the table gives both names:
| verifier | what it does | forgeries it accepts |
|---|---|---|
verify_naive (v0) | uses the algorithm header["alg"] names | both |
verify_blocklist (v1) | same, but refuses "none" | key confusion |
verify_allowlist (v2) | same, but accepts only HS256 and RS256 | key confusion |
verify_strict (v3) | never reads header["alg"] | neither |
The third row is the surprise. The alg: none forgery is well known, and verify_blocklist already stops it. verify_allowlist is what a careful engineer writes next: it accepts only two real, strong, standard algorithms. It still returns role: admin for a token made by someone who knows no secret at all. A shorter or stricter list does not fix this. The fix is to stop reading alg out of the token, which is one line (section 6.4).
The feature that makes this possible is called algorithm agility: the token itself says which algorithm should check it. Agility is useful. It lets a system move from one algorithm to another gradually, without upgrading every issuer and every verifier on the same day. It also means the verifier takes an instruction from a field the attacker writes.
By the end you should be able to:
A server wants to hand a client a small piece of state, such as "you are alice, you are an admin, until 3pm". The client carries it around and sends it back later, and the server wants to accept it without a database lookup. The token has to survive a round trip through someone who may want to change it.
That is a message-authentication problem, and a message authentication code (MAC) solves it. A MAC is a short tag computed from the message and a secret key. Without the key you cannot compute a valid tag, so any change to the message is caught. HMAC is the standard way to build a MAC from a hash function, and in an HS256 token the signature is exactly this HMAC tag. If JWT were only this, the toy would demonstrate HMAC and nothing else.
JWT adds a second requirement on top: algorithm agility, from section 1. Systems run for years, and algorithms get retired. If every token is checked with one fixed algorithm, changing it means upgrading every issuer and every verifier at the same moment. If the token names its algorithm, the system can change gradually. So JSON Web Signature (JWS), the signing format underneath JWT, puts the algorithm name in the header, and the verifier reads the header first.
Several goals pull against each other here, which is why more than one design is defensible:
alg field is covered by the signature, but the verifier has to read it before it can check the signature. That ordering is what this toy is about.exp claim, its expiry time, and that claim sits inside the very token you are checking. Section 8 lists revocation among the things this toy leaves out.You don't need deep cryptography for this page, but it relies on the seven ideas below.
| Concept | Where it's used here | One source |
|---|---|---|
The alg header |
verify_naive, jwt.py:156, the line this page is about |
RFC 7515 §4.1.1 |
| The JWS signing input | split, jwt.py:135: the encoded segments and the dot, not the parsed JSON |
RFC 7515 §5.1 |
| HMAC accepts any bytes as a key | hs256, jwt.py:81-85, which is why a public key works as a secret |
RFC 7518 §3.2 |
| Key-pair signatures publish the verification key | PUBLIC_KEY, jwt.py:66-71 |
RFC 7518 §3.3 |
| base64url | b64e and b64d, jwt.py:37-44; padding is stripped and never sent |
RFC 7515 Appendix C |
| Constant-time comparison | hmac.compare_digest, jwt.py:160; it takes the same time however many bytes match, and section 6.5 measures whether that matters here |
hmac.compare_digest |
| Textbook RSA | rs256_sign and rs256_check, jwt.py:88-103; insecure on purpose (section 7.3) |
RFC 7518 §3.3 |
Two of these rows produce the result. Row 1 is the bug: the verifier reads an instruction from a document the attacker wrote. Row 3 is what lets an attacker use the hole without any secret: hmac.new(key, ...) accepts any bytes as a key, so a key that was published on purpose works as an HMAC secret. Neither row is a weakness in the cryptography. HMAC-SHA-256 is not broken here. Every forged token on this page passes because its signature is genuinely correct for the key the server used.
Let's picture the problem before any code. A JWT is three base64url segments joined by dots, and the signature covers the first two segments as text:
This is circular. To check the signature, the verifier must first know which algorithm to use, and the only place that is written is inside the part it has not checked yet.
Here are the two forgeries side by side. The demo prints them as FORGERY A and FORGERY B, so the diagram uses the same labels:
The alg: none forgery works because a check is missing. The key-confusion forgery works because a check passes, using a key the server itself publishes, and that is the one to remember. In one sentence: an RSA public key is safe to publish because it can only verify, but hand that same key to HMAC, where one key both signs and verifies, and anyone who can verify can also sign.
jwt.py is 212 lines: nine small functions and four verifiers. Its docstrings number the verifiers v0 to v3, as in the table in section 1. We'll read it in this order.
Just above this excerpt, the docstring says that the header names the algorithm the verifier should use. "That last sentence" refers to it.
That last sentence is the toy. The header is a document the attacker hands
you, and a verifier that reads `alg` out of it is asking the attacker how the
attacker should be checked. Four verifiers here, in the order a codebase
usually acquires them:
verify_naive dispatch on header["alg"]
verify_blocklist ... but refuse "none"
verify_allowlist ... but only allow HS256 and RS256
verify_strict never read header["alg"] at all
The first three all accept a forged token. See commentary section 6.
Why four verifiers instead of two? A broken one and a fixed one would have been 19 lines shorter: the middle two are jwt.py:172-190. Those two show how the bug survives the fixes people actually write. Each verifier is a competent response to the failure of the one before, and the third one is still wrong. Section 7.1 argues this choice in more detail.
# PUBLIC_KEY is what the server holds in order to *verify* RS256, and what
# anybody at all can fetch from a /.well-known/jwks.json. It is bytes,
# because that is how a real verifier receives it: a PEM blob, a JWKS entry,
# a file read off disk. Section 6.3 is about what happens when those bytes
# reach a function that was expecting an HMAC secret.
PUBLIC_KEY = _json({"kty": "RSA", "n": N, "e": E})
PRIVATE_KEY = _json({"kty": "RSA", "n": N, "d": D})
# The shared secret for a symmetric deployment. Section 6.7 uses it to show
# where the attack stops working.
SECRET = b"correct horse battery staple"
PUBLIC_KEY is plain bytes, not a parsed key object, and the whole toy depends on that choice. It is also realistic. A real verifier receives its key as a PEM string (the text format for keys that begins with -----BEGIN), as an entry in a JWKS (a JSON Web Key Set, the JSON document where a service publishes its public keys), or as a file it just read. rs256_check parses those bytes as an RSA key. hs256 uses the same bytes directly as an HMAC secret. So one value means two different things in two functions, and nothing in its type says which was intended.
_json writes compact JSON with sorted keys, so the bytes are the same on every run. Printed, the public key holds only e, the public exponent, and n, the modulus:
That is 182 bytes, and all of them are safe to publish. PRIVATE_KEY holds d, the private exponent, instead of e, and shares n. It is the only value in the file that must stay secret.
def hs256(signing_input, key):
"""HMAC-SHA-256. `key` is arbitrary bytes -- any bytes at all, which is
exactly the property section 6.3 turns into a forgery.
"""
return hmac.new(key, signing_input, hashlib.sha256).digest()
def rs256_sign(signing_input, priv):
"""Textbook RSA: s = h^d mod n, over the bare digest. Deterministic,
unpadded, and insecure -- see the module docstring.
"""
k = json.loads(priv)
h = int.from_bytes(hashlib.sha256(signing_input).digest(), "big")
return pow(h, k["d"], k["n"]).to_bytes(64, "big")
def rs256_check(signing_input, sig, pub):
"""s^e mod n == h. Note the asymmetry that makes RS256 worth having:
this needs only `pub`, while rs256_sign needs `priv`.
"""
k = json.loads(pub)
h = int.from_bytes(hashlib.sha256(signing_input).digest(), "big")
return pow(int.from_bytes(sig, "big"), k["e"], k["n"]) == h
These 23 lines hold the whole vulnerability, in the contrast between the first function and the other two.
rs256_sign needs d. rs256_check needs only e and n. That gap is what public-key cryptography means: the ability to verify is separated from the ability to sign, so the verification key can be published safely.
hs256 has no such gap. HMAC is symmetric: the same key both creates and checks a tag. And it accepts any byte string as that key. Put those two facts together and the attack follows. Take the key that was published because it can only verify, and give it to an algorithm where verifying and signing use the same key.
pow(h, d, n) and pow(s, e, n) use Python's three-argument pow, which computes modular exponentiation. That is all of RSA. It is also textbook RSA, with no padding. Real RSA signatures first wrap the hash in a fixed format, the padding, which blocks known attacks. Leaving it out is fine for this toy and dangerous in production. Section 7.3 explains why the toy accepts that cost.
split, and what the signature actually coversdef split(token):
"""(header, payload, signature bytes, signing input). The signing input
is the first two segments and the dot between them, as ASCII -- not the
decoded JSON, which is why re-serialising a header breaks a signature.
"""
h, p, s = token.split(".")
return json.loads(b64d(h)), json.loads(b64d(p)), b64d(s), f"{h}.{p}".encode()
Look at the fourth return value, f"{h}.{p}".encode(). The signing input, the bytes the signature is computed over, is built from the segments while they are still encoded. The verifier does not parse the JSON and encode it again. Section 5.1 of RFC 7515 requires this, for a practical reason. JSON has no single canonical form, since key order and whitespace are free. A verifier that re-encoded the parsed header would get different bytes whenever its JSON library formatted differently from the signer's, and honest tokens would fail.
This matters for the rest of the page: an attacker cannot edit the header of an existing token. Changing one character of the header segment changes the signing input, so the signature no longer matches; section 7.4 shows the run. The header is signed data. The problem is not that someone can modify it. The problem is that the verifier follows its instruction before checking that nobody changed it.
verify_naive, and the line this page is aboutdef verify_naive(token, key, now=0):
"""v0. Asks the token how the token should be checked.
Returns the payload on success, None on rejection. Read the first two
lines of the body: `alg` comes out of the header, and the header came
from whoever sent the token.
"""
header, payload, sig, signing_input = split(token)
alg = header["alg"]
if alg == "none":
ok = sig == b""
elif alg == "HS256":
ok = hmac.compare_digest(hs256(signing_input, key), sig)
elif alg == "RS256":
ok = rs256_check(signing_input, sig, key)
else:
return None
if not ok:
return None
if "exp" in payload and payload["exp"] < now:
return None
return payload
This is v0. Read it slowly.
Everything after the line alg = header["alg"] is done well. hmac.compare_digest is the constant-time comparison: it takes the same time however many bytes match, so the time it takes reveals nothing. The RSA check is real. The expiry claim exp is checked. Unknown algorithms fall through to the else branch and are rejected, so this verifier does not accept "HS512" or "foo". The signature comparison does not use ==.
None of it helps. The second line of the body chooses which of those careful checks runs, and it chooses by reading a field the attacker wrote.
Notice also if "exp" in payload. The expiry is enforced only when the token contains an exp claim. That is a second, separate bug, and it is there on purpose. Section 7.5 tests it on its own, because exploiting it needs the real signing key: it is a mismatch between what the issuer sends and what the verifier requires, not a forgery.
The verifier returns the payload rather than True on success. That lets the demo print which role it accepted, ADMIN or ok:user, so you see what the attacker actually gained, not just that a check passed (section 7.6).
verify_blocklist and verify_allowlist, the two fixes that don't workdef verify_blocklist(token, key, now=0):
"""v1. The reflex fix, and the one the industry shipped in 2015:
refuse the algorithm that turned out to be a hole.
"""
header, _payload, _sig, _si = split(token)
if header["alg"] == "none":
return None
return verify_naive(token, key, now)
def verify_allowlist(token, key, now=0, allowed=("HS256", "RS256")):
"""v2. The careful fix. Name the algorithms you are prepared to accept,
up front, and reject everything else. Both of these are real, strong,
standard algorithms. This verifier is still broken -- section 6.3.
"""
header, _payload, _sig, _si = split(token)
if header["alg"] not in allowed:
return None
return verify_naive(token, key, now)
Both run their own check and then call verify_naive. That makes the comparison fair. verify_naive, verify_blocklist and verify_allowlist run exactly the same verification code, so any difference in their results comes from the one added check and nothing else.
verify_blocklist is the patch the ecosystem shipped in 2015, after Tim McLean disclosed both forgeries. verify_allowlist is what you write if you read section 3.2 of RFC 8725 ("applications MUST only allow the use of cryptographically current algorithms") and stop there. It is a real improvement: it rejects none, and it rejects every unknown or retired algorithm for good.
It does nothing against the key-confusion forgery, because HS256 is on the list. HS256 has to be on the list, or the experiment would test nothing. A list that contains only RS256 no longer lets the token choose anything, so it behaves like verify_strict (section 5.7). Section 7.1 explains this choice.
verify_strict, and why passing the algorithm is not enoughdef verify_strict(token, key, alg, now=0):
"""v3. The caller names the algorithm. `header["alg"]` is never read --
the header is now signed *data*, not an instruction.
`alg` must be the algorithm that matches `key`. Passing "HS256" here
together with an RSA public key reproduces the whole bug (section 7.2),
so the pairing is the fix, not the keyword.
"""
_header, payload, sig, signing_input = split(token)
if alg == "HS256":
ok = hmac.compare_digest(hs256(signing_input, key), sig)
elif alg == "RS256":
ok = rs256_check(signing_input, sig, key)
else:
raise ValueError(alg)
if not ok:
return None
if payload.get("exp", 0) < now:
return None
return payload
Compare it with verify_naive in section 5.5, line by line. The branches are the same, the signature functions are the same, and compare_digest is the same. Only three things differ:
_header and never used, and the underscore says so on purpose;alg arrives as an argument from the server;payload.get("exp", 0) instead of if "exp" in payload, so a token with no expiry is treated as expired instead of valid forever.An unknown algorithm raises ValueError(alg) here instead of returning None, and that is deliberate. alg now comes from the server, so an unrecognised value is a bug in the server's own configuration, not a bad token. Returning None would turn a typo in your config into an outage that looks like every user failing to log in.
It's tempting to conclude that passing the algorithm as an argument is the fix, and that is a mistake. Section 7.2 calls verify_strict(..., "HS256", ...) with the RSA public key and gets the forgery back exactly. The fix is that alg and key are chosen together, by the party that owns both. Section 3.1 of RFC 8725 says the same: "each key MUST be used with exactly one algorithm, and this MUST be checked when the cryptographic operation is performed."
demo.py creates one honest RS256 token and runs four acts, numbered 0 to 3, against all four verifiers. In its output each verifier has a short label: v0 naive is verify_naive, v1 -none is verify_blocklist, v2 allow is verify_allowlist, and v3 strict is verify_strict. ok:user means the verifier accepted a token with role user, ADMIN means it accepted a token with role admin, and reject means it refused the token. peek decodes a token without checking it (section 6.6).
python3 demo.py
Act 0 is a real signature. The claims are sub=alice, role=user, exp=1700003600. The toy's clock, NOW, is fixed at 1_700_000_000, and the token expires 3600 seconds later, which gives 1700003600. All four verifiers accept it. That matters, because it shows that verify_strict rejects the forgeries in acts 2 and 3 without rejecting every token.
Act 1 changes the payload, keeps the old signature, and every verifier rejects the result. Both changes are small: alice to alicf changes one byte, and "user" to "admin" is the change an attacker would actually want (test_tampering_the_payload_is_caught).
This is exactly what a MAC is for, so nobody predicts otherwise. Act 1 is here so you see the signature check working before you see it defeated. When acts 2 and 3 succeed, you know the signature check itself was not broken.
alg: none forgery, and a verifier that never uses a keyGREEDY is the attacker's payload: sub alice, role admin, expiring a year after NOW. The whole forgery is one call:
forged_none = jwt.encode(GREEDY, "none", None)
The None in the key position is deliberate: there is no key. The token is two base64url segments, a trailing dot, and 0 signature bytes. verify_naive takes the none branch, sets ok = sig == b"", and returns the claims.
How much does the verifier depend on its key here? Check C1 of sweep.py passes it four different keys:
Four different keys, one of them empty, and all four give ADMIN. The key plays no part in the decision (test_alg_none_forgery_ignores_the_key_entirely). So alg: none is not a weak signature. It is no signature at all, accepted through the same function call as a real one.
This is the well-known bug, published by Tim McLean in March 2015, and verify_blocklist stops it with one line. Libraries patched it soon after. If the toy stopped here, it would be a history lesson.
This is the central result of the page. The forgery is again one call:
forged_conf = jwt.encode(GREEDY, "HS256", jwt.PUBLIC_KEY)
The attacker signs with HS256 and uses the server's RSA public key as the HMAC secret. Here is the full token:
And here is verify_allowlist, which accepts only HS256 and RS256, accepting it:
Let's work out why. The three segments decode to:
The attacker computes HMAC-SHA256(PUBLIC_KEY, signing_input). The server holds the same PUBLIC_KEY so it can check RS256 tokens. The header says HS256, so the server takes the HS256 branch and computes the same thing:
(1b144e… in hexadecimal is GxRO95… in base64url, the third segment of the token above.)
The two values are equal because both sides ran the same function on the same inputs. No cryptography was broken. The 32 bytes in that token are a correct HMAC-SHA-256 tag. The attacker's whole advantage is that the server publishes the key.
How much secret did the forgery need? Check C9 of sweep.py counts it:
The 1456 bits are the 182-byte public key from section 5.2, and the 224 bits are the 28-byte SECRET. The attacker wrote every one of the 144 bytes the server accepted, using zero bits of secret. The honest issuer needed a 509-bit private exponent to produce a token the server would accept.
The idea to keep is this: an allowlist limits which algorithms run. It says nothing about which key each algorithm runs with, and the attack runs an allowed algorithm with the wrong key.
oneline.py is one verifier with a single line switched between two versions. Everything else stays the same: the same allowlist, the same compare_digest, the same RSA check, the same expiry check:
def verify(token, key, server_alg, trust_the_token):
header, payload, sig, signing_input = jwt.split(token)
if trust_the_token:
alg = header["alg"] # LINE A: the token decides
else:
alg = server_alg # LINE B: the server decides
if alg not in ("HS256", "RS256"):
return None
if alg == "HS256":
ok = hmac.compare_digest(jwt.hs256(signing_input, key), sig)
else:
ok = jwt.rs256_check(signing_input, sig, key)
if not ok or payload.get("exp", 0) < NOW:
return None
return payload
python3 oneline.py
The honest token is accepted in both rows, so the second version is not simply stricter. It has stopped taking instructions from the token it is checking.
We expected to demonstrate both of these claims and could not. We report them anyway, because a page that showed only the results that worked would mislead you.
Claim 1: "block none, and the attacker sends nOnE." This is repeated everywhere, and against verify_blocklist as written it does not work. Check C2 of sweep.py tries five spellings. It runs each one against verify_blocklist as shipped, and against a variant whose parser normalises the algorithm name first:
Every row in the left column is a rejection. The reason is in section 5.5: the branches in verify_naive also compare exact strings, so "nOnE" matches none of the three strings "none", "HS256" and "RS256", and reaches return None. The bypass needs a second ingredient, a parser that normalises alg before choosing a branch while the blocklist compares the raw string:
def verify_normalising(token, key, now=0):
"""v1, but with a parser that is liberal in what it accepts:
canonicalise `alg` before dispatch, and blocklist the exact string.
"""
header, payload, sig, si = jwt.split(token)
if header["alg"] == "none":
return None
alg = header["alg"].strip().upper()
if alg == "NONE":
ok = sig == b""
So the accurate statement is not "blocklists can be bypassed with case variants". It is this: a blocklist and a normalising parser compare different strings, and the attacker sends a string where they disagree. That tells you where to look in your own code: not at the blocklist alone, but at whether the blocklist's check and the parser's check see the same string.
Claim 2: "== leaks the signature one byte at a time." The usual reason given for hmac.compare_digest is that == stops at the first byte that differs. An attacker could then measure response times and recover a signature byte by byte. We tried to measure it with check C8 of sweep.py:
There is no trend. A 1-byte prefix match (31.65 ns) and a 31-byte prefix match (31.41 ns) take the same time, and the 31-byte one is slightly faster, the wrong direction for a leak. The whole spread across the four prefix lengths is 1.95 ns, or 6.6%.
One timing run is not enough to conclude anything, so the last line repeats the whole four-way measurement ten more times. It counts how often the four medians come out in increasing order. If == leaked a per-byte signal, that count would be 10/10. It is 1/10, about what you get by ranking four numbers drawn from the same distribution. (The line good is full -> False checks that the correct signature, good, and the full-match candidate, full, are separate objects. If they were the same object, Python could skip the comparison, and the timing would mean nothing.)
The reason is that Python does not compare bytes objects in a Python loop. Two bytes objects of equal length go to the C function memcmp, which compares 32 bytes in a couple of vector instructions, with no per-byte early exit that we can observe. The measurable difference runs the other way: averaged over the four rows, hmac.compare_digest takes 40.11 ns per call here, against 31.08 for ==, so it is about 9 ns, or 30%, slower.
Use compare_digest anyway. The toy does, at jwt.py:160 and jwt.py:203. Use it because it costs about 9 ns and makes the timing question go away, not because this measurement supports the usual story.
Python 3.15.0a8, on a laptop with other programs running. They are a measurement, not a universal claim. Different hardware, a different interpreter, a comparison written in pure Python, or a signature compared across a network can each change the answer. The timing attack is real wherever the comparison is a loop. Run python3 sweep.py on your own machine and read your own check C8 before you rely on this.
Can anyone read a JWT without the key? Check C10 of sweep.py calls peek, which takes no key, on the honest token:
peek (jwt.py:138-143) takes no key and checks nothing, because reading a JWT needs neither. A signature proves that nobody changed the claims. It does nothing to stop anybody reading them, and zero of the token's 186 bytes are encrypted. Anything you would not print in a log does not belong in a JWT payload. Put it in a JWE, the encrypted format, or keep it on the server behind an opaque session id.
We measured two boundaries. Together they let you decide whether your own system is exposed.
Boundary 1: the attacker needs the exact bytes of the key. Knowing the public key as a number is not enough. The attacker needs the exact byte string the server passes to HMAC. Check C3 of sweep.py tries six versions of the key:
One row succeeds and five fail. A cleverer attacker cannot get partial credit for a nearly right key, because changing any byte of an HMAC key changes the whole tag. A PEM file with a trailing newline and the same file without one are two different keys to HMAC. In the real-world bug, this is why exploitability depends on the library: the attacker has to guess a format, how the server stores and loads its key, but no secret (test_key_confusion_needs_the_bytes_exactly).
This also gives you a practical defence. Each JWKS entry carries a key id, kid. If the verifier looks up a parsed key object by kid and passes that object, not raw bytes, to the signature check, there is no byte string for the attacker to guess.
Boundary 2: a system that uses only shared secrets is immune to key confusion. Check C4 of sweep.py runs a system that uses only HS256 with a secret key:
The key-confusion forgery uses a published key as if it were a shared secret. If your system publishes no verification key, there is nothing to misuse, and verify_allowlist holds. The attacker is back to guessing a secret, which is the problem the cryptography was designed for. The last row is the exception. The alg: none forgery uses no key at all, so it works against every kind of system, which is why it needed its own fix and got one first.
So ask three questions of any verifier you review:
alg out of the token? If not, neither forgery applies.none.python3 test_jwt.py
There are fourteen tests, written with plain assert statements and no pytest. test_alg_none_forgery_beats_the_naive_verifier and test_key_confusion_beats_the_allowlist check the two forgeries. test_key_confusion_needs_the_bytes_exactly and test_symmetric_deployments_are_immune_to_key_confusion check the two boundaries from section 6.7. Two more, test_wrong_signatures_are_still_rejected and test_honest_tokens_round_trip, guard against a "fix" that simply rejects every token. test_rsa_round_trips_and_is_not_a_stub checks that the toy RSA is real: a signature made with D checks out under E, and N really is the 511-bit product of the two hardcoded primes. Without that test, section 6.3 would prove nothing, because a fake RS256 could not show that the public key is genuinely public.
The short version of this toy is verify_naive and verify_strict: broken and fixed, 19 lines shorter, same conclusion. We built the middle two anyway, because they carry the lesson.
verify_blocklist exists because it is the fix libraries shipped in 2015, and because a reader who knows only the alg: none story needs to see that story end before act 3 can surprise them. verify_allowlist exists because it is a good answer. It is what a careful engineer writes and what a plain reading of section 3.2 of RFC 8725 asks for, and it is still wrong. Without it, the page would be arguing against a verifier nobody would write.
The lesson reaches beyond JWT: limiting which operations an attacker may request is a different control from taking away the attacker's ability to choose. verify_allowlist does the first. Only verify_strict does the second.
Why is allowed=("HS256", "RS256") and not just ("RS256",)? An allowlist with one entry no longer lets the token choose anything. It behaves like verify_strict, so it would prove nothing. The interesting case is a system that genuinely supports two algorithms, which is the case algorithm agility exists for.
The tempting one-line summary of this page is "pass the algorithm explicitly". That is not enough, and we ran it to check, with check C5 of sweep.py:
Row 2 is verify_strict, the "fixed" verifier that never reads header["alg"], returning ADMIN for the same forged token. The server chose the algorithm, but it chose one that does not belong to the key it holds.
That is why section 3.1 of RFC 8725 is worded the way it is:
Libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms when performing cryptographic operations. The library MUST ensure that the "alg" or "enc" header specifies the same algorithm that is used for the cryptographic operation. Moreover, each key MUST be used with exactly one algorithm, and this MUST be checked when the cryptographic operation is performed.
That paragraph makes three requirements, and its last sentence forbids exactly what row 2 does. In a real library the types enforce it: keys are typed objects, and an HMAC function will not accept an RSA public key at all. The toy passes raw bytes on purpose, so the failure is visible (section 5.2).
test_strict_must_pair_the_alg_with_the_key checks rows 2 and 3.
The alternative was a fake RS256, "HMAC with a key the attacker doesn't have", which would have saved twelve lines. We built real RSA instead: pow(h, d, n) to sign, pow(s, e, n) == h to check, and a 511-bit modulus from two hardcoded 256-bit primes.
The reason is that section 6.3 depends on the verification key being genuinely public. With a fake, "the attacker knows the verification key" is a claim you have to accept. With real RSA you can check it: rs256_check needs only e and n, and rs256_sign needs d.
The cost is a warning in the module docstring, because this RSA is insecure in ways unrelated to the toy's point. It has no PKCS#1 or PSS padding (the standard schemes that make RSA signatures safe), a modulus small enough to factor, and a bare digest raised to a power directly. Unpadded RSA has real attacks of its own. None of them appear on this page, and none are needed. Key confusion does not depend on the padding scheme. Check C3 in section 6.7 shows why: what decides success is the exact serialisation of the key, not the mathematics.
A side benefit is that textbook RSA has no random padding, so every signature on this page is reproducible. PSS would have cost that.
Is the header protected at all? "The attacker rewrites the header" makes it sound unprotected, so we checked. Check C6 of sweep.py edits the header of a valid token. typ is the header field that names the token type:
Editing one field of a valid token's header breaks its signature at every verifier, because the signing input is the encoded header text (section 5.4). An attacker cannot take a token they were legitimately given and change its label.
What they can do is sign a new token. That is the difference between acts 1 and 3: act 1 edits an existing token and fails, and act 3 creates a new one and succeeds. So the whole attack comes down to one question: can the attacker compute a valid tag? The answer becomes yes as soon as a published key reaches a shared-secret algorithm.
exp is checked two different waysverify_naive checks if "exp" in payload and payload["exp"] < now. verify_strict checks if payload.get("exp", 0) < now. The difference is deliberate, and it shows a second, smaller bug. Check C7 of sweep.py:
An expiry that is enforced only when the claim is present is optional: the issuer can leave it out. Row 4 is a token that verify_naive still accepts ten years after it was issued.
This is not a forgery. It needs the real signing key, and it is a mismatch between what the issuer sends and what the verifier requires. That is why it is an experiment in sweep.py rather than an act in the demo. It is here because it shows a general rule: every claim in the payload is optional until a verifier requires it. The same applies to aud (the intended audience), iss (the issuer) and nbf (not valid before), none of which this toy implements.
test_exp_is_only_an_expiry_if_it_is_required checks the same behaviour.
TrueEvery verifier here returns the claims on success and None on failure. Returning a boolean would be more conventional, and test_jwt.py would be shorter.
Returning the payload lets the demo print ADMIN instead of True, and that one word shows you what the forgery bought, not merely that a check passed. It also removes a temptation the boolean version creates: code that verifies the token and then parses the claims out of it a second time. If the two decodes disagree, for example because one JSON parser keeps the first of two duplicate keys and the other keeps the last, the code checks one set of claims and acts on another.
The cost is a Python detail you have to read carefully: None is falsy, and so is an empty payload {}. A production interface would raise an exception on failure instead of returning a special value, which is what real libraries do.
kid, and no JWKS. Real systems put a key id, kid, in the header and look the key up by it. That is both a defence (boundary 1 in section 6.7: a parsed key object has no byte string to guess) and a new attack surface. kid is another header field the attacker writes, and it has been used for path traversal, SQL injection and directory-listing attacks when a server feeds it to a file read or a database query. That deserves its own toy.aud, iss, nbf or jti (audience, issuer, not-before time, and a unique token id). The toy has only exp, and only for section 7.5. A real verifier must check the audience. Otherwise a token issued for service A can be replayed at service B, a whole class of bug this toy does not cover.now is an argument. Real verifiers read a clock, and then need a small allowance for the clock difference between issuer and verifier, a setting with its own trade-off.Authorization header, and nothing on the network. The forged token is a Python string handed to a Python function.zip: DEF header asks the verifier to decompress the payload, and a small payload that decompresses to gigabytes has caused denial of service in real systems. None of that is here.Answer each question before you expand it. Each answer can be worked out from the source, and each was checked by running it.
Your verifier accepts only RS256: you checked, and the allowlist is ("RS256",). Are you safe from the key-confusion forgery in section 6.3?
Yes. An allowlist with exactly one entry behaves like verify_strict (section 7.1). The forged token declares HS256, fails the membership test, and never reaches a key.
Notice what did the work. It was not that the list is short. It was that the list can no longer choose between two algorithms, so the attacker's alg field no longer affects anything. As soon as you add a second algorithm, for example during a key rotation, you have verify_allowlist again. This row of the demo's summary table shows what that costs:
The v2 allow column is verify_allowlist, returning ADMIN (section 7.1).
The attacker knows your RSA public key. It is in your JWKS, which is the point of publishing it. Does that mean the key-confusion forgery works against you?
Not necessarily. The attacker needs the exact bytes your verifier passes to HMAC, not the key as a number. Check C3 of sweep.py:
Five of the six fail. A PEM file with a trailing newline and one without are different keys to HMAC. If your verifier looks up a parsed key object by kid and passes that object, there is no byte string to guess at all (section 6.7, boundary 1).
This changes how hard the bug is to exploit, not whether you have it. Fix the bug.
You follow the advice and pass the algorithm explicitly: verify_strict(token, key, "HS256"). key is your RSA public key, because that is the variable your verifier already had. Are you fixed?
No. You have written the same bug out by hand. Check C5 of sweep.py:
Row 2 is the forged token, accepted by the "fixed" verifier. What protects you is not the argument. It is that the algorithm and the key are chosen together, by the party that owns both. Section 3.1 of RFC 8725 says it as "each key MUST be used with exactly one algorithm" (section 7.2).
Your system uses only HS256, with a strong shared secret and an allowlist. Which of the two forgeries still works?
Neither works against verify_allowlist. The alg: none forgery still works against any verifier that does not reject none, such as verify_naive, whatever your keys are. Check C4 of sweep.py:
The key-confusion forgery needs a published key to use as a shared secret, and a system with only shared secrets publishes none. The alg: none forgery uses no key at all, so your choice of keys does not affect it (section 6.7, boundary 2).
You use == instead of hmac.compare_digest to compare signatures. Measure the timing attack on this toy. What do you find?
On this machine, it does not reproduce:
There is no trend: 1 matching byte and 31 matching bytes take the same time, and the 31-byte match is slightly faster. Repeated ten times, the four medians come out in increasing order once, where a real per-byte leak would give 10/10. Python compares equal-length bytes with memcmp, which shows no per-byte early exit at this size. The measurable difference runs the other way: compare_digest is about 9 ns (about 30%) slower per call.
Use compare_digest regardless. It costs about 9 ns and settles the question. But don't repeat the usual story as though this toy showed it. This is also one machine and one Python build, and a comparison written as a Python loop, or different hardware, can behave differently (section 6.5).
You are reviewing a service. Its verifier calls a library function that takes (token, key) and returns claims, with no algorithm argument. You can see nothing else. What do you write in the review?
That you cannot approve it without reading the implementation, because the interface allows only two designs and one of them is broken.
If the function is not told which algorithm to use, there are two possibilities. Either it has one algorithm hardcoded, which is safe from both forgeries but means the caller can never change algorithms, or it reads alg from the token, which is verify_naive. There is no third possibility. So the parameter list alone is enough to raise the question, and the body decides the answer.
Then ask the three questions from section 6.7: does it read alg; does one key parameter serve both a shared-secret and a key-pair algorithm; and are the exact bytes of that key public. The first decides whether the bug exists. The other two decide how easily it can be exploited.
Every link below was fetched and confirmed live when this was written.
RS256 … parameter value can be changed into HS256, and some libraries would try to validate the signature using HMAC-SHA256 and using the RSA public key as the HMAC shared secret." Its section 3.1, "Perform Algorithm Verification", describes verify_strict, and its last sentence is the point of section 7.2 here.[McLean]. Both forgeries in this toy come from it. This sentence states the whole of section 6.3: "If a server is expecting a token signed with RSA, but actually receives a token signed with HMAC, it will think the public key is actually an HMAC secret key."node-jsonwebtoken library, and the identifier RFC 8725 cites.alg header. Its section 5.1 defines the signing input as the encoded segments joined by a period, which section 5.4 here reads in the code. Its Appendix C is the base64url-without-padding routine that b64e and b64d implement.exp as OPTIONAL, which is why a verifier that checks it only when present has no real expiry. Read it next to section 7.5 here.SECRET does not meet. Its section 3.3 is RSASSA-PKCS1-v1_5, which rs256_sign would be if it had padding. Its section 3.6 defines "none".kid, jku and x5u header fields, which tell the verifier which key to use or where to fetch it. This toy leaves those out (section 8).hmac.compare_digest. The function measured in section 6.5, and the standard library's statement of what it does and does not promise. Read it before deciding what our numbers mean on your hardware.