Defending AI Agents
עברית Join waitlist
Menu

On-ramp · Lesson 08

A JWT is signed claims, and a check has an order

A server receives Authorization: Bearer eyJhbGciOi…. It splits on dots, base64-decodes the middle, reads "role": "admin" and lets the call through. It never checked the third part. The token was written by the caller, a minute ago, with a text editor.

Three parts, two of them just JSON

A JSON Web Token has three base64url-encoded parts joined by dots: header, payload (the claims) and signature (RFC 7519, 2015; RFC 7515, 2015). Decoding is not secret: base64url is an encoding, not encryption. This is a real token minted with a throwaway key, and the standard library reads it:

import base64, json
tok = ("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
       "eyJpc3MiOiJodHRwczovL2F1dGguYWNtZS5leGFtcGxlIiwic3ViIjoiYWdlbnQtNyIsImF1ZCI6Imh0dHBzOi8vY3JtLmFjbWUuZXhhbXBsZS9tY3AiLCJzY29wZSI6ImNybTpyZWFkIiwiaWF0IjoxMDAwLCJleHAiOjEzMDB9."
       "2Vc6vcSxz-JiNHCGQqh18ZrUCUKVOqZghKK27YDicRo")
part = lambda s: json.loads(base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)))
print(part(tok.split(".")[0]))   # {'alg': 'HS256', 'typ': 'JWT'}
print(part(tok.split(".")[1]))
# {'iss': 'https://auth.acme.example', 'sub': 'agent-7', 'aud': 'https://crm.acme.example/mcp',
#  'scope': 'crm:read', 'iat': 1000, 'exp': 1300}
Claim Name Means
iss issuer who minted and signed it
sub subject whom it is about (here, an agent, not a person)
aud audience which server may accept it
exp, iat, nbf expiry, issued, not-before the time window, in seconds since 1970
scope scope what it permits (RFC 9068 carries it for OAuth access tokens)

The signature binds the first two parts

The signature is computed over header.payload with a key. HS256 uses one shared secret (HMAC-SHA-256): anyone who can verify can also forge. RS256 and ES256 use a private key to sign and a public key to verify, so a resource server can check tokens without being able to mint them. Change one character of the payload and the signature stops matching.

The check, in order

The verifier below is the shortest honest one (HS256 only). Its order is the lesson:

import hashlib, hmac

def verify(tok, key, aud, now):
    h, p, s = tok.split(".")
    if part(h)["alg"] != "HS256":                       # 1. the algorithm we configured
        raise ValueError("algorithm")
    good = base64.urlsafe_b64encode(
        hmac.new(key, f"{h}.{p}".encode(), hashlib.sha256).digest()).rstrip(b"=").decode()
    if not hmac.compare_digest(good, s):                # 2. the signature
        raise ValueError("signature")
    c = part(p)
    if c["iss"] != "https://auth.acme.example":         # 3. the issuer
        raise ValueError("issuer")
    if aud not in ([c["aud"]] if isinstance(c["aud"], str) else c["aud"]):   # 4. the audience
        raise ValueError("audience")
    if c["exp"] <= now:                                 # 5. the time
        raise ValueError("expired")
    return c                                            # 6. only now read sub and scope

The numbers below are its steps:

  1. Algorithm: the one you configured, never the one the token's header asks for.
  2. Signature: recompute and compare in constant time.
  3. Issuer: the issuer you trust. With keys for several issuers, choose the key by the iss claimed, or check that the key that verified belongs to it: a valid signature from the wrong issuer's key must fail.
  4. Audience: you are in it (Module 3, lesson 10).
  5. Time: exp is in the future; allow seconds, not minutes, of clock skew.
  6. Then read sub and scope.

Run with the key b"demo-key-not-a-secret", it accepts the token above at t = 1100 for audience https://crm.acme.example/mcp, and refuses these four, for these reasons:

Presented Refused because
to https://cal.acme.example/mcp audience
at t = 1300 expired (exp is exclusive)
payload edited to crm:write, original signature signature
header {"alg": "none"}, no signature algorithm

Expert: the attacks all live in step 1

alg: none is a valid algorithm in the RFC, meaning "unsecured". A library that honours it accepts a token no one signed. The second is key confusion: a server expects RS256 and verifies with its public key; an attacker sets alg: HS256, signs with the public key as the HMAC secret, and a library that picks the algorithm from the header verifies it. JWT Best Current Practices (RFC 8725, 2020) lists both and the cure: pin the algorithm per key, and refuse anything else. Two header parameters invite the same mistake: kid (which key to use) and jku (a URL to fetch a key set from). A verifier that follows either as the token says has let the token choose its own judge.

Check yourself

  1. A server holds keys for issuers A and B and accepts a signature made with either. A token signed with B's key claims iss A and "role": "admin". Why is it more dangerous to the server than a token with no signature, and which step stops it?
  2. A server verifies the signature and exp but not aud, and one authorization server issues tokens for 20 resource servers that all skip the check. At how many servers can a token stolen from one of them be replayed, before and after they add step 4?
  3. A verifier reads alg from the token and picks a library function for it. Describe, in one sentence each, none and key confusion against it.
Answers
  1. A token with no signature fails at step 1 or 2 on any sound verifier. One signed with B's key passes step 2, because the server holds that key, so "role": "admin" arrives looking authentic. Step 3 stops it, because it binds the issuer to the key: B's key did not sign for A, so a token claiming iss A fails.
  2. Before: at all 20, since every one verifies the same authorization server's signature and none checks the audience. After step 4: at one, the server named in its aud; if it was stolen from that server, nowhere else.
  3. none: the attacker sets "alg": "none", sends an empty signature, and the verifier calls its "unsecured" function, which accepts claims nobody signed. Key confusion: the server holds an RS256 public key; the attacker sets "alg": "HS256" and signs with that public key as the HMAC secret, and the verifier, running HMAC with the key it holds, finds the signature valid.