← Back to FastAPI, page 5

fastapi-0097 · Hard senior

How do you validate JWT access tokens in FastAPI using RS256, a JWKS endpoint, key rotation, and audience and issuer checks?

Resource servers verify tokens with the issuer's public keys, fetched from a JWKS endpoint and cached, and selected by the kid in the token header. Pin the allowed algorithms (RS256), require exp, iss and aud, and verify them explicitly. Rotation works by publishing the new key beside the old one, signing with the new one, and removing the old one after the longest token lifetime passes. Refresh the JWKS cache on unknown kid, rate-limited.

Full answer

Why RS256 (asymmetric): the issuer (an identity provider such as Auth0, Keycloak or Cognito) signs with a private key; any API can verify with the public key without being able to mint tokens. HS256 shares one secret between signer and verifier, so every verifier could forge tokens.

Validation steps in the API:

  1. Read the unverified header to get kid and alg. Never trust alg from the token: call jwt.decode(..., algorithms=["RS256"]) with a fixed list. This blocks alg: none and HS256 key-confusion attacks (an attacker signing with the public key as an HMAC secret).
  2. Look up the key by kid in a cached JWKS (PyJWKClient(url, cache_keys=True) fetches /.well-known/jwks.json). On an unknown kid, refetch at most every few minutes (rotation), then fail.
  3. Verify the signature and the claims: exp (and nbf) with small leeway, iss equals your issuer exactly, aud includes your API identifier (audience prevents tokens meant for another API being accepted), optionally scope/roles for authorisation and token_use or typ.
  4. Put validated claims in a dependency (Depends(current_claims)) and enforce scopes with Security(current_claims, scopes=[...]). Return 401 with WWW-Authenticate: Bearer for invalid tokens, 403 for insufficient scope.

Key rotation:

  • Add the new public key to the JWKS (two keys with different kid), start signing with the new key, wait until all old tokens expire (max token lifetime plus clock skew), then remove the old key.
  • Emergency revocation of a key: remove it immediately; tokens signed with it fail. Short-lived access tokens (5 to 15 minutes) limit exposure; use refresh tokens, and token introspection or deny lists only where immediate revocation is needed.
  • Cache JWKS with a TTL, and never fetch it on every request (latency and outage risk). Keep serving from the cache if the endpoint is briefly down.

Operational: fetch JWKS over HTTPS only from a configured issuer URL (do not follow a jku header from the token), synchronise clocks (NTP), and never log tokens.

python
import time

import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from jwt import PyJWKSet
from jwt.algorithms import RSAAlgorithm

ISSUER, AUDIENCE = "https://login.schoolabe.example/", "https://api.schoolabe.example"


def new_key():
    private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    pem = private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
    return pem, private.public_key()


def jwk(public_key, kid):
    d = RSAAlgorithm.to_jwk(public_key, as_dict=True)
    d.update(kid=kid, use="sig", alg="RS256")
    return d


def issue(pem, kid, **overrides):
    claims = {"iss": ISSUER, "aud": AUDIENCE, "sub": "asha", "exp": int(time.time()) + 300, "scope": "grades:read"}
    claims.update(overrides)
    return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": kid})


def verify(token, jwks):
    kid = jwt.get_unverified_header(token)["kid"]
    keys = {k.key_id: k for k in PyJWKSet.from_dict(jwks).keys}
    if kid not in keys:
        return "rejected: unknown kid"
    try:
        claims = jwt.decode(token, keys[kid].key, algorithms=["RS256"], audience=AUDIENCE, issuer=ISSUER,
                            options={"require": ["exp", "iss", "aud"]})
        return f"ok: {claims['sub']}"
    except jwt.InvalidTokenError as exc:
        return f"rejected: {type(exc).__name__}"


pem_a, pub_a = new_key()
jwks = {"keys": [jwk(pub_a, "key-2026-01")]}
token = issue(pem_a, "key-2026-01")
print("valid token:", verify(token, jwks))
print("expired:", verify(issue(pem_a, "key-2026-01", exp=int(time.time()) - 60), jwks))
print("wrong audience:", verify(issue(pem_a, "key-2026-01", aud="https://other-api.example"), jwks))
print("wrong issuer:", verify(issue(pem_a, "key-2026-01", iss="https://evil.example/"), jwks))
print("hs256 with public key as secret:", end=" ")
forged = jwt.encode({"iss": ISSUER, "aud": AUDIENCE, "exp": int(time.time()) + 300}, "not-a-real-secret", algorithm="HS256", headers={"kid": "key-2026-01"})
print(verify(forged, jwks))

pem_b, pub_b = new_key()                                             # rotation: publish both keys
jwks = {"keys": [jwk(pub_a, "key-2026-01"), jwk(pub_b, "key-2026-07")]}
print("old token during rotation:", verify(token, jwks))
print("new token:", verify(issue(pem_b, "key-2026-07"), jwks))
jwks = {"keys": [jwk(pub_b, "key-2026-07")]}                           # old key retired
print("old token after retirement:", verify(token, jwks))

Standalone script. Run it with `python file.py`; it generates throwaway RSA keys. Requires `pip install pyjwt cryptography`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, PyJWT 2.15.1): valid token: ok: asha expired: rejected: ExpiredSignatureError wrong audience: rejected: InvalidAudienceError wrong issuer: rejected: InvalidIssuerError hs256 with public key as secret: rejected: InvalidAlgorithmError old token during rotation: ok: asha new token: ok: asha old token after retirement: rejected: unknown kid

Key points

  • RS256 lets APIs verify without being able to sign
  • Pin algorithms; never trust the token's alg
  • Select the key by kid from a cached JWKS; refetch on unknown kid
  • Verify exp, iss and aud explicitly
  • Rotate by publishing both keys until old tokens expire

Common mistakes

  • Accepting whatever algorithm the token header names
  • Skipping audience or issuer checks
  • Fetching the JWKS on every request or never refreshing it
  • Removing the old key before old tokens expire
  • Following a jku header from an untrusted token
  • Logging full tokens

Follow-ups

  • How do you enforce scopes with Security?
  • How would you revoke a token before it expires?
  • What are the differences between ID tokens and access tokens?

Tips

  • Explain why asymmetric
  • List the claims to verify
  • Describe rotation steps