Delegated Login with OAuth 2.0 and OpenID Connect, and Stopping Token Replay
Use the OAuth 2.0 authorization code flow with PKCE and OpenID Connect; validate access tokens at the API with JWKS keys and scopes, validate ID tokens and their nonce against the login that started them, and limit replay with short lifetimes and sender-constrained tokens.
Contentsand lesson path
On this page
- Why it matters
- OAuth 2.0, OpenID Connect and the code flow: PKCE, state and nonce
- Validating access tokens at the API
- At login: validate the ID token and its nonce, link identities safely
- Limiting replay: short lifetimes and sender-constrained tokens
- Check your understanding
- Apply it
- Review prompt
Lessons of Authentication & Authorization
- Identity, Credentials and Permission Models (RBAC, ABAC, ReBAC) Concept · 20 min
- Storing Passwords So a Breach Is Not a Disaster Worked example · 20 min
- Sessions, Tokens or API Keys? Trade-offs and Pitfalls Concept · 30 min
- Delegated Login with OAuth 2.0 and OpenID Connect, and Stopping Token Replay Concept · 30 min
- Lab: Roles and Ownership Checks in FastAPI Lab · 30 min
- Check: Spot the Authorization Bug Knowledge check · 10 questions
What you will learn
- Explain OAuth 2.0 authorization code with PKCE and OIDC; validate API access tokens for the configured token type (signature or introspection, issuer, audience, expiry and scopes), validate an ID token and its nonce against the initiating login transaction, and explain how short lifetimes and sender-constrained tokens limit replay.
Prerequisites: HTTP & APIs
01. Why it matters
"Sign in with Google" and company single sign-on move passwords, resets and MFA to an identity provider (IdP). Your app and your API then depend on tokens the IdP issues, and a common class of bug is accepting a token that should have been refused: an ID token used as an API credential, a token minted for another API, an ID token replayed from another login, or a bearer token copied out of a log.
This lesson explains the flow, then builds the checks on both sides: the API that validates access tokens, and the app that validates the ID token at login. It ends with the two tools that limit replay of a stolen token: short lifetimes and sender-constrained tokens.
02. OAuth 2.0, OpenID Connect and the code flow: PKCE, state and nonce
- OAuth 2.0 (RFC 6749) is for delegated access. The client app receives an access token and presents it to a resource server (your API), which checks that the token allows the request, through its scopes such as
invoices:read. - OpenID Connect (OIDC) adds login on top. The client also receives an ID token, a signed JWT that tells the client who signed in: issuer (
iss), subject (sub), audience (aud, the client's own ID) and expiry (exp).
The rule that follows: an ID token is for the client app, an access token is for the API. Your API accepts only access tokens whose audience is that API. An ID token carries the client ID as its audience, so an API that checks aud refuses it.
In the authorization code flow the browser is sent to the IdP, the user signs in, and the IdP redirects back with a short-lived code that the client exchanges for tokens. Three random values protect it:
- PKCE (RFC 7636): the client creates a secret
code_verifier, sends its SHA-256 hash (code_challenge) withcode_challenge_method=S256in the redirect, and sends the verifier itself when exchanging the code. Always send the method: without it the server assumesplain, where the challenge is the verifier itself, and RFC 7636 requiresS256from any client that can compute it. A stolen code is useless without the verifier. RFC 9700 requires PKCE for public clients and recommends it for confidential ones; use it everywhere. - state: ties the response to the browser that started the login, which stops login CSRF, where an attacker gets a victim signed in to the attacker's account.
- nonce (OIDC): the IdP copies it into the ID token, so the client can check that this ID token was issued for this login and not replayed from another one.
import base64
import hashlib
import secrets
def generate_pkce_pair() -> tuple[str, str]:
"""
Generate high-entropy code_verifier and SHA-256 code_challenge.
RFC 7636 specifies a 43-128 character URL-safe verifier.
"""
# 1. Generate 64 cryptographically random bytes
code_verifier = secrets.token_urlsafe(64)
# 2. Hash verifier using SHA-256
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
# 3. Base64url encode without padding
code_challenge = (
base64.urlsafe_b64encode(digest)
.decode("ascii")
.rstrip("=")
)
return code_verifier, code_challenge03. Validating access tokens at the API
Many IdPs issue access tokens as JWTs in the format of RFC 9068. That profile marks them with the header typ: at+jwt, so an ID token cannot pass as one, and requires the resource server to check the issuer, an audience naming this API, the signature with a key from the IdP's published key set (its jwks_uri) and expiry. Each key in the set has a key ID (kid), and each token names the kid that signed it, which lets the IdP rotate keys.
To run the example without a real IdP, a small fake one generates P-256 keys, serves them as a JWKS on 127.0.0.1 and mints tokens. Use the virtual environment from the previous lessons (FastAPI, pytest, httpx2 and pyjwt[crypto]):
"""A test identity provider: signing keys, a JWKS endpoint and token minting."""
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import jwt
from cryptography.hazmat.primitives.asymmetric import ec
ISSUER = "https://idp.example.test"
class FakeIdP:
def __init__(self):
self.keys = {} # kid -> private key
self.jwks_requests = 0
self.rotate("key-1")
idp = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
idp.jwks_requests += 1
body = json.dumps(idp.jwks()).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args): # keep test output quiet
pass
self.server = HTTPServer(("127.0.0.1", 0), Handler) # port 0: any free port
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.jwks_url = f"http://127.0.0.1:{self.server.server_port}/jwks.json" def rotate(self, kid: str) -> None:
self.keys[kid] = ec.generate_private_key(ec.SECP256R1())
self.kid = kid # new tokens are signed with this key
def jwks(self) -> dict:
keys = []
for kid, key in self.keys.items():
jwk = jwt.algorithms.ECAlgorithm.to_jwk(key.public_key(), as_dict=True)
keys.append(jwk | {"kid": kid, "use": "sig", "alg": "ES256"})
return {"keys": keys}
def mint(self, typ: str = "at+jwt", **claims) -> str:
now = int(time.time())
payload = {"iss": ISSUER, "iat": now, "exp": now + 300} | claims
return jwt.encode(payload, self.keys[self.kid], algorithm="ES256",
headers={"kid": self.kid, "typ": typ})The API fetches keys with PyJWT's PyJWKClient, which caches the key set. In PyJWT 2.15.1 an unknown kid triggers one re-fetch, but no more than once per 30-second cooldown, so a flood of tokens with random kid values cannot hammer the IdP:
import jwt
from fastapi import Depends, FastAPI, Header, HTTPException
ISSUER = "https://idp.example.test"
API_AUDIENCE = "https://api.example.test"
jwks_client: jwt.PyJWKClient | None = None # set at start-up from configuration
def configure(jwks_url: str) -> None:
global jwks_client
# Caches the key set for 5 minutes; an unknown kid triggers one re-fetch
jwks_client = jwt.PyJWKClient(jwks_url, cache_jwk_set=True, lifespan=300)
def invalid_token(why: str) -> HTTPException:
return HTTPException(401, why, headers={
"WWW-Authenticate": f'Bearer error="invalid_token", error_description="{why}"'})
def validate_access_token(token: str) -> dict:
try:
typ = jwt.get_unverified_header(token).get("typ", "")
if typ.lower() not in ("at+jwt", "application/at+jwt"): # RFC 9068
raise invalid_token("not an access token")
key = jwks_client.get_signing_key_from_jwt(token) # chosen by kid
return jwt.decode(token, key, algorithms=["ES256"], audience=API_AUDIENCE,
issuer=ISSUER,
options={"require": ["exp", "iss", "aud", "sub", "scope"]})
except jwt.PyJWTError as exc: # bad signature, claims or unknown kid
raise invalid_token(type(exc).__name__) from exc
def require_scope(scope: str):
def dependency(authorization: str | None = Header(default=None)) -> dict:
scheme, _, token = (authorization or "").partition(" ")
if scheme.lower() != "bearer" or not token:
raise HTTPException(401, "Bearer token required",
headers={"WWW-Authenticate": "Bearer"})
claims = validate_access_token(token)
if scope not in claims["scope"].split():
challenge = f'Bearer error="insufficient_scope", scope="{scope}"'
raise HTTPException(403, "insufficient_scope",
headers={"WWW-Authenticate": challenge})
return claims
return dependency
app = FastAPI()
@app.get("/invoices")
def list_invoices(claims: dict = Depends(require_scope("invoices:read"))):
return {"owner": claims["sub"], "invoices": []}Failures follow RFC 6750: a bad, expired or wrong-audience token gets 401 with error="invalid_token", and a valid token without the needed scope gets 403 with error="insufficient_scope", so the client knows that a new token will not help unless it asks for more access.
Some IdPs issue opaque access tokens: random strings with no readable claims. The API then asks the IdP through token introspection (RFC 7662): it POSTs the token as a form field to the introspection endpoint, authenticating itself, and reads back JSON. Accept the token only if active is true, then check aud, scope and exp as above. For an inactive token, the IdP should return only {"active": false}, without saying why. You may cache a response briefly, never past its exp, and every second of caching is a second in which a revoked token still works.
import pytest
from fastapi.testclient import TestClient
import resource_server as rs
from fake_idp import FakeIdP
AUD = rs.API_AUDIENCE
@pytest.fixture
def idp():
idp = FakeIdP()
rs.configure(idp.jwks_url)
yield idp
idp.server.shutdown()
def call(token):
client = TestClient(rs.app)
return client.get("/invoices", headers={"Authorization": f"Bearer {token}"})
def test_valid_token_and_jwks_fetched_once(idp):
token = idp.mint(aud=AUD, sub="usr_1", scope="invoices:read")
assert [call(token).status_code for _ in range(3)] == [200, 200, 200]
assert idp.jwks_requests == 1 # later calls used the cached key set
def test_new_kid_is_fetched_once_the_cooldown_allows(idp):
assert call(idp.mint(aud=AUD, sub="usr_1", scope="invoices:read")).is_success
idp.rotate("key-2") # the IdP signs with a brand-new key
token = idp.mint(aud=AUD, sub="usr_1", scope="invoices:read")
assert call(token).status_code == 401 # unknown kid, inside the cooldown
assert idp.jwks_requests == 1
rs.jwks_client.cooldown_duration = 0 # as if the 30 s cooldown had passed
assert call(token).is_success
assert idp.jwks_requests == 2 # one re-fetch found key-2
def test_missing_scope_gets_403_insufficient_scope(idp):
r = call(idp.mint(aud=AUD, sub="usr_1", scope="profile:read"))
assert r.status_code == 403
assert 'error="insufficient_scope"' in r.headers["www-authenticate"]
@pytest.mark.parametrize("claims, typ", [
({"aud": "https://other-api.example.test", "scope": "invoices:read"}, "at+jwt"),
({"aud": AUD, "scope": "invoices:read", "exp": 1}, "at+jwt"),
({"aud": "web-app", "nonce": "n-1"}, "JWT"), # an ID token
], ids=["wrong-aud", "expired", "id-token"])
def test_bad_tokens_get_401(idp, claims, typ):
r = call(idp.mint(typ=typ, sub="usr_1", **claims))
assert r.status_code == 401
assert 'error="invalid_token"' in r.headers["www-authenticate"]04. At login: validate the ID token and its nonce, link identities safely
The client keeps a login transaction for each login it starts, keyed by state and holding the nonce it sent. When the IdP redirects back, the client exchanges the code (with the PKCE verifier) for tokens; this example skips that HTTP call and lets the tests play the IdP. OIDC Core says the ID token's iss must exactly match the IdP, aud must contain the client ID, the current time must be before exp, and the nonce claim must equal the value sent in the request:
import hmac
import secrets
import time
from urllib.parse import urlencode
import jwt
ISSUER = "https://idp.example.test"
CLIENT_ID = "web-app"
PENDING: dict[str, dict] = {} # state -> login transaction (server-side store)
TXN_TTL = 10 * 60
class LoginError(Exception):
pass
def start_login() -> str:
state, nonce = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
PENDING[state] = {"nonce": nonce, "expires": time.time() + TXN_TTL}
# PKCE code_challenge omitted here; see the earlier section
query = urlencode({"response_type": "code", "client_id": CLIENT_ID,
"scope": "openid", "state": state, "nonce": nonce,
"redirect_uri": "https://app.example.test/callback"})
return f"{ISSUER}/authorize?{query}"
def finish_login(state: str, id_token: str,
jwks: jwt.PyJWKClient) -> tuple[str, str]:
"""Validate the ID token from the token response; return (iss, sub)."""
txn = PENDING.pop(state, None) # pop: a transaction completes once
if txn is None or txn["expires"] < time.time():
raise LoginError("unknown, used or expired login transaction")
try:
key = jwks.get_signing_key_from_jwt(id_token)
claims = jwt.decode(id_token, key, algorithms=["ES256"],
audience=CLIENT_ID, issuer=ISSUER,
options={"require": ["exp", "iat", "sub", "nonce"]})
except jwt.PyJWTError as exc:
raise LoginError(type(exc).__name__) from exc
if not hmac.compare_digest(claims["nonce"], txn["nonce"]):
raise LoginError("nonce does not match this login")
return claims["iss"], claims["sub"]pop removes the transaction, so a callback replayed with the same state fails, and the nonce comparison rejects an ID token issued for any other login, including the attacker's own. The tests attack each check:
from urllib.parse import parse_qs, urlparse
import jwt
import pytest
import oidc_login as app
from fake_idp import FakeIdP
@pytest.fixture
def idp():
app.PENDING.clear()
idp = FakeIdP()
yield idp
idp.server.shutdown()
def begin():
"""Start a login and read state and nonce back out of the redirect URL."""
query = parse_qs(urlparse(app.start_login()).query)
return query["state"][0], query["nonce"][0]
def id_token(idp, nonce, aud=app.CLIENT_ID):
return idp.mint(typ="JWT", aud=aud, sub="248289761001", nonce=nonce)
def test_matching_nonce_signs_in(idp):
state, nonce = begin()
jwks = jwt.PyJWKClient(idp.jwks_url)
assert app.finish_login(state, id_token(idp, nonce), jwks) == (
"https://idp.example.test", "248289761001")
def test_id_token_from_another_login_is_rejected(idp):
jwks = jwt.PyJWKClient(idp.jwks_url)
_, other_nonce = begin() # the attacker's own login
state, _ = begin() # the victim's login
with pytest.raises(app.LoginError, match="nonce"):
app.finish_login(state, id_token(idp, other_nonce), jwks)
def test_replayed_callback_is_rejected(idp):
jwks = jwt.PyJWKClient(idp.jwks_url)
state, nonce = begin()
token = id_token(idp, nonce)
app.finish_login(state, token, jwks)
with pytest.raises(app.LoginError, match="used"):
app.finish_login(state, token, jwks)
def test_id_token_for_another_client_is_rejected(idp):
jwks = jwt.PyJWKClient(idp.jwks_url)
state, nonce = begin()
with pytest.raises(app.LoginError, match="InvalidAudienceError"):
app.finish_login(state, id_token(idp, nonce, aud="other-app"), jwks)python -m pytest -v --no-header -p no:cacheprovider============================= test session starts ==============================
collecting ... collected 10 items
test_oidc_login.py::test_matching_nonce_signs_in PASSED [ 10%]
test_oidc_login.py::test_id_token_from_another_login_is_rejected PASSED [ 20%]
test_oidc_login.py::test_replayed_callback_is_rejected PASSED [ 30%]
test_oidc_login.py::test_id_token_for_another_client_is_rejected PASSED [ 40%]
test_resource_server.py::test_valid_token_and_jwks_fetched_once PASSED [ 50%]
test_resource_server.py::test_new_kid_is_fetched_once_the_cooldown_allows PASSED [ 60%]
test_resource_server.py::test_missing_scope_gets_403_insufficient_scope PASSED [ 70%]
test_resource_server.py::test_bad_tokens_get_401[wrong-aud] PASSED [ 80%]
test_resource_server.py::test_bad_tokens_get_401[expired] PASSED [ 90%]
test_resource_server.py::test_bad_tokens_get_401[id-token] PASSED [100%]
============================= 10 passed in 17.41s ==============================Suppose Bob has a password account as [email protected]. An attacker creates an account with the same email at a provider that does not verify email ownership and signs in to your app with it. If your backend links logins by email, the attacker is now in Bob's account. To prevent this:
- Store federated identities as
(iss, sub)pairs, which are stable and unique per provider, not as email strings. - Trust an email only when the provider asserts
"email_verified": true, and even then do not merge automatically. - When an incoming login matches an existing account's email, ask the user to sign in to that account first, then link the new
(iss, sub)to it.
05. Limiting replay: short lifetimes and sender-constrained tokens
Every check so far accepts a valid bearer token from whoever holds it. If one leaks into a log or a proxy, the copy works until exp. Short lifetimes, minutes rather than hours, shrink that window but do not close it. RFC 9700 says servers should go further and sender-constrain access tokens, binding each token to a key that only the real client holds:
- DPoP (RFC 9449): the client keeps a key pair and sends, with every request, a
DPoPheader holding a short JWT (a proof) of typedpop+jwt, signed with its private key and carrying the public key. The proof's claims name the HTTP method (htm), the URL (htu), the time (iat), a unique ID (jti) and a hash of the access token (ath). The access token carriescnf.jkt, the SHA-256 thumbprint of that public key. The API checks the signature, method, URL and age of the proof, can refuse ajtiit has already seen, and checks thatathand the thumbprint match. The request usesAuthorization: DPoP <token>, and a bad proof getsinvalid_dpop_proof. - Mutual TLS (RFC 8705): the client authenticates the TLS connection with a certificate, and the token carries
cnfwithx5t#S256, the SHA-256 hash of that certificate. The API compares it with the certificate on the connection and answers 401invalid_tokenon a mismatch.
A thief with only the token cannot produce either proof. Neither helps when the attacker runs code inside the client: RFC 9449 notes that injected script can create fresh proofs while the client is online, so preventing XSS still matters.
06. Check your understanding
07. Apply it
In your practice API, replace the fake IdP with a test identity provider such as a local Keycloak or your IdP's test tenant. Point configure at its jwks_uri, set ISSUER and API_AUDIENCE from configuration, and keep the negative tests: an ID token offered to the API, a token for another audience, an expired token and a missing scope. In the web client, store state, nonce and the PKCE verifier per login and validate the ID token as finish_login does. Check in your IdP's documentation whether it supports DPoP or mTLS-bound tokens for your clients.
The next lesson is a lab: role and ownership checks in FastAPI.
08. Review prompt
Without looking back, list the checks an API runs on a JWT access token, which status and error it returns when each fails, and how it finds the signing key. Explain how the nonce and state tie an ID token to one login. Finally, explain why a sender-constrained token is useless to someone who copied it from a log, and what it does not protect against.
References
- RFC 9700: Best Current Practice for OAuth 2.0 Security
- RFC 7636: Proof Key for Code Exchange by OAuth Public Clients (PKCE)
- OpenID Connect Core 1.0 incorporating errata set 2
- RFC 9068: JWT Profile for OAuth 2.0 Access Tokens
- RFC 7662: OAuth 2.0 Token Introspection
- RFC 6750: OAuth 2.0 Bearer Token Usage
- RFC 9449: OAuth 2.0 Demonstrating Proof of Possession (DPoP)
- RFC 8705: OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens
- OWASP Cheat Sheet Series: OAuth 2.0 Protocol Cheat Sheet
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.