TExcelTAD

JSON Web Tokens Built by Hand

A server-side session needs a lookup on every request. Many APIs, and every OpenID Connect sign-in, use a different idea: the server hands the client a signed statement ("this is user 42, valid until 10:15, for the orders API") and any service holding the verification key can check it without a database. The common format is the JSON Web Token (JWT). JWTs are simple enough to build with a few lines of standard library code, and building one by hand is the best way to see what the signature protects, what it doesn't (the contents are readable by anyone), and why the verifier, not the token, decides whether it is safe. The next lesson breaks badly written verifiers.

Definitions (RFC 7519 JWT, RFC 7515 JWS, RFC 7518 JWA)

  • Structure: BASE64URL(header) . BASE64URL(payload) . BASE64URL(signature), where Base64url drops = padding and uses -_ instead of +/. The signature is computed over the ASCII string header.payload.
  • Header: {"alg": "HS256", "typ": "JWT", "kid": "…"}. alg names the algorithm: HS256 (HMAC-SHA256, one shared secret), RS256 (RSA PKCS#1 v1.5 + SHA-256), PS256, ES256 (ECDSA P-256), EdDSA; kid names the key.
  • Registered claims: iss issuer, sub subject (the user id), aud audience (who the token is for), exp expiry, nbf not before, iat issued at, jti unique id. All times are seconds since the Unix epoch.
  • JWS vs JWE: a signed JWT (JWS) is readable by anyone; only an encrypted JWT (JWE) hides its contents. Almost every JWT you meet is a JWS.

Building, reading and verifying an HS256 token

The secret is fixed so the output is stable; real secrets are at least 256 random bits from secrets.token_bytes(32). The clock is fixed too.

python · try it yourself
import base64, hashlib, hmac, json

def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def b64url_decode(s: str) -> bytes:
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

SECRET = b"lab-only-hs256-secret-0123456789abcdef"
NOW = 1_790_000_000

def sign(payload: dict) -> str:
    header = {"alg": "HS256", "typ": "JWT"}
    signing_input = b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + \
                    b64url(json.dumps(payload, separators=(",", ":")).encode())
    sig = hmac.new(SECRET, signing_input.encode(), hashlib.sha256).digest()
    return signing_input + "." + b64url(sig)

def verify(token: str, audience: str, now=NOW) -> dict:
    h, p, s = token.split(".")
    header = json.loads(b64url_decode(h))
    if header.get("alg") != "HS256":                       # the verifier decides the algorithm
        raise ValueError("unexpected alg")
    expected = hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest()
    if not hmac.compare_digest(expected, b64url_decode(s)):
        raise ValueError("bad signature")
    claims = json.loads(b64url_decode(p))
    if claims.get("iss") != "https://auth.lab.test":
        raise ValueError("wrong issuer")
    if claims.get("aud") != audience:
        raise ValueError("wrong audience")
    if not isinstance(claims.get("exp"), int) or claims["exp"] <= now:
        raise ValueError("expired or no exp")
    return claims

token = sign({"iss": "https://auth.lab.test", "sub": "user-42", "aud": "orders-api",
              "role": "customer", "iat": NOW, "exp": NOW + 900})
print("token:", token[:60] + "...")
print("parts:", [len(x) for x in token.split(".")])

# Anyone can read the payload: no key needed.
print("decoded without the key:", json.loads(b64url_decode(token.split(".")[1])))

print("verify:", verify(token, "orders-api")["sub"])

# Tampering: change the role and keep the old signature.
h, p, s = token.split(".")
claims = json.loads(b64url_decode(p)); claims["role"] = "admin"
forged = h + "." + b64url(json.dumps(claims, separators=(",", ":")).encode()) + "." + s
for label, tok, aud, now in [("forged role", forged, "orders-api", NOW),
                              ("other audience", token, "billing-api", NOW),
                              ("16 minutes later", token, "orders-api", NOW + 960)]:
    try:
        verify(tok, aud, now)
        print(f"{label}: accepted")
    except ValueError as e:
        print(f"{label}: rejected ({e})")
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F...
parts: [36, 158, 43]
decoded without the key: {'iss': 'https://auth.lab.test', 'sub': 'user-42', 'aud': 'orders-api', 'role': 'customer', 'iat': 1790000000, 'exp': 1790000900}
verify: user-42
forged role: rejected (bad signature)
other audience: rejected (wrong audience)
16 minutes later: rejected (expired or no exp)

Three lessons are in that output. The payload decodes without the key: never put secrets, passwords or personal data you wouldn't show the user into a JWT. The signature covers every byte of header and payload, so changing role breaks it. And the claim checks are not automatic: a token with a valid signature was still rejected for the wrong audience and after expiry only because verify checked aud and exp explicitly.

A check against the standard

RFC 7515 Appendix A.1 publishes a complete HS256 example: a header with a line break in it, a payload, a key (as a JWK k value) and the resulting signature. Recomputing it confirms that the signing input is the Base64url text exactly as transmitted, not re-serialised JSON:

python · try it yourself
import base64, hashlib, hmac

def b64url(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def unb64url(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

header = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9"
payload = "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
key = unb64url("AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow")
sig = b64url(hmac.new(key, f"{header}.{payload}".encode(), hashlib.sha256).digest())
print("header :", unb64url(header))
print("payload:", unb64url(payload))
print("signature:", sig)
print("matches RFC 7515 A.1:", sig == "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")
header : b'{"typ":"JWT",\r\n "alg":"HS256"}'
payload: b'{"iss":"joe",\r\n "exp":1300819380,\r\n "http://example.com/is_root":true}'
signature: dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
matches RFC 7515 A.1: True

Sessions versus JWTs

Server-side session Self-contained JWT
Lookup per request yes (store) no (signature check)
Revocation delete the record hard: wait for exp, or keep a denylist of jti / a per-user token version
Size a short id hundreds of bytes to kilobytes
Who can verify the app with the store any service with the key (good for many APIs)
Typical use browser sessions for one app access tokens between services, OIDC ID tokens

Short-lived JWT access tokens (5–15 minutes) plus a revocable refresh token is the usual compromise; it is exactly what TAD issues to ExcelTAD (15-minute access tokens, rotating refresh tokens, see the PKCE lesson).

How JWT misuse is detected

  • Decode every token you see while testing (a JWT starts with eyJ, the Base64 of {"): look for personal data, internal roles, long or missing exp, missing aud.
  • Where tokens travel: in URLs (then in logs, Referer, browser history), in localStorage alongside third-party scripts, in error messages.
  • Code review: decoding without verifying (jwt.decode(token, options={"verify_signature": False}), jwt.decode in PyJWT without algorithms=), verifying the signature but not aud/iss/exp, weak secrets (secret, the app name). Weak HMAC secrets can be guessed offline from one token, so they must be long and random.
  • Logs: tokens with unknown kid, signature failures in bursts, tokens used long after iat.

How JWTs are used safely

  1. Use a maintained library; pass the allowed algorithms explicitly, plus the expected iss and aud, and require exp.
  2. HS256 only when issuer and verifier are the same service and share a 256-bit random secret; asymmetric (ES256, EdDSA, RS256) when many services verify.
  3. Short lifetimes, refresh tokens that rotate, and a revocation mechanism for logout and incidents.
  4. Send tokens in the Authorization: Bearer header, never in URLs.

Pitfalls

  • "It's signed, so it's encrypted." It is not.
  • Trusting claims added for convenience (role, is_admin) after the user's role changed: the token keeps the old role until it expires.
  • Clock skew: allow a small leeway (30–60 s) on exp/nbf, not hours.

Practice

1. Decode the payload eyJzdWIiOiJ1c2VyLTciLCJyb2xlIjoiYWRtaW4ifQ by hand or with Python.

base64.urlsafe_b64decode("eyJzdWIiOiJ1c2VyLTciLCJyb2xlIjoiYWRtaW4ifQ==") gives {"sub":"user-7","role":"admin"}. No key is needed, which is the point: readable, not secret.

2. A user is banned at 10:00; their JWT access token expires at 10:55. How do you stop them before then?

Shorter lifetimes in the first place, plus a check the API does anyway: a per-user token_version (or banned flag) looked up from a cache, or a denylist of jti values until their exp. Refuse the refresh token so no new access token is issued.

Practice problems in 21 languages: Read a JWT Claim (Without Trusting It), Base64 and Base64url Encoding.

Test yourself

What does the signature of a JWS protect?

  1. The confidentiality of the payload
  2. The integrity of header and payload: any change breaks it
  3. The token's transport
  4. Nothing

In the example, why was a correctly signed token rejected for billing-api?

  1. The signature was wrong
  2. The verifier checked aud and the token was issued for orders-api
  3. The token had expired
  4. HS256 is insecure

What is the main weakness of long-lived self-contained JWTs?

  1. They are slow to verify
  2. They can't easily be revoked before exp
  3. They can't contain a user id
  4. Browsers reject them

A JWT appears in a URL query string. Why is that a finding?

  1. URLs can't be that long
  2. URLs end up in logs, history and Referer headers, leaking the bearer token
  3. It disables the signature
  4. It is required by OAuth