The OAuth 2.0 authorization code flow with PKCE, and the JWT checks an API must make, end to end with nothing hidden in a library.
Companion code for my LinkedIn articles
OAuth 2.0 in Modern Applications โ
Microsoft Entra ID โ
sequenceDiagram
autonumber
participant U as User's browser
participant C as Client app
participant A as Authorization server
participant R as API (resource server)
C->>C: verifier = random 32 bytes<br/>challenge = BASE64URL(SHA256(verifier))
C->>U: redirect to /authorize?client_id, redirect_uri,<br/>scope, state, code_challenge (S256)
U->>A: sign in + consent
A->>U: 302 to registered redirect_uri?code&state
U->>C: code + state (client checks state)
C->>A: POST /token: code + code_verifier
A->>A: SHA256(verifier) == stored challenge?<br/>code unused, unexpired, same client + redirect_uri?
A->>C: access token (JWT signed RS256)
C->>R: GET /laps Authorization: Bearer <JWT>
R->>R: alg allowlisted, kid in JWKS, signature,<br/>iss, aud, exp/nbf (with leeway), scope
R->>C: 200, or 401 / 403 with WWW-Authenticate
git clone https://github.com/atonyhonesto/oauth2-pkce-jwt-walkthrough.git cd oauth2-pkce-jwt-walkthrough python demo.py # real HTTP servers on localhost, then nine attacks python -m unittest -v # 13 tests, including the RFC 7636 test vector
Real output:
Authorization server up at http://127.0.0.1:35451 (RSA-2048 key 710c059f generated in 1.0 s)
1. Client makes a PKCE pair and sends the user to /authorize with the challenge (never the verifier)
code_verifier CaOxbzW2SRMu1Ndo... (kept in the app)
code_challenge q8Wdvqsqb5QtNDA6... = BASE64URL(SHA256(verifier))
2. User signs in; server answers 302 redirect to the registered callback
code 2uFv1Q33ctocsRvn... state matches what we sent: True
3. Client redeems code + verifier at /token -> 200
access token: 675-char JWT, expires in 300 s
claims: {'iss': 'http://127.0.0.1:35451', 'aud': 'api://race-data', 'sub': 'tony', 'scope': 'laps.read', 'azp': 'race-dashboard'}
4. Client calls the API with the bearer token -> 200 {'user': 'tony', 'laps': [{'car': '24', 'lap': 1, 'time_s': 41.25}]}
Attacks, and what stops them
intercepted code, redeemed without the verifier -> 400 PKCE verification failed
legitimate code replayed a second time -> 400 unknown, used or expired code
authorize with an unregistered redirect_uri -> 400 unknown client or redirect_uri
token with scopes edited after signing -> 401 bad signature
token re-headed as alg "none", signature removed -> 401 algorithm 'none' not allowed
token that expired ten minutes ago -> 401 expired
valid token minted for a different API -> 401 token is for 'api://billing', not this API
valid token without the laps.read scope -> 403 missing scope 'laps.read'
no token at all -> 401 Bearer realm="race-data"
| Defence | Stops | Where |
|---|---|---|
| PKCE (S256) | A stolen authorization code being redeemed by someone else (mobile apps, SPAs, malicious browser extensions) | pkce.py, /token in servers.py |
| Single-use, short-lived codes | Replay of a code from logs or history | state.codes.pop(...), 60 s TTL |
| Exact redirect URI match | Codes delivered to an attacker's site (open redirect) | /authorize and /token |
state parameter |
Login CSRF: an attacker's code injected into your session | client.py |
| Algorithm allowlist | alg: none and RS256โHS256 key-confusion forgeries |
ALLOWED_ALGS in jwt.py |
Signature with key from JWKS by kid |
Edited claims; supports key rotation | Validator.validate |
iss + aud |
A real token from another issuer, or for another API, being replayed here | Validator.validate |
exp / nbf with leeway |
Old tokens; small clock skew doesn't cause outages | leeway_s = 60 |
| Scope check โ 403 | Authenticated but not authorised callers; 401 vs 403 tells the client what to do | required_scope |
| Here | Entra ID |
|---|---|
/.well-known/openid-configuration |
https://login.microsoftonline.com/<tenant>/v2.0/.well-known/openid-configuration |
CLIENTS["race-dashboard"] |
App registration: client ID, redirect URIs, platform type (SPA / mobile / web) |
Scope laps.read on api://race-data |
Expose an API on the API's app registration; client gets API permissions and consent |
/jwks with one key |
jwks_uri with several keys; Entra rotates them, so cache and refresh on unknown kid |
rsa.py + jwt.py |
MSAL on the client, Microsoft.Identity.Web / JwtBearer middleware on a .NET API |
rsa.py implements RSA and PKCS#1 v1.5 by hand so the signature check is visible. It is for learning. Real systems use a vetted library and keys held in an HSM or Key Vault.
oauthdemo/
b64.py base64url helpers
rsa.py key generation, RS256 sign and verify
pkce.py verifier and S256 challenge
jwt.py encode, JWKS entry, Validator
servers.py authorization server and protected API (http.server)
client.py authorize, callback, redeem, call
demo.py the full flow, then nine attacks
tests/ unit tests and end-to-end flow tests
Built by Tony Honesto, cloud & integration engineer. More articles and companion code: github.com/atonyhonesto ยท article-labs ยท LinkedIn