Repository navigation
OAuth 2 0 and OpenID Connect Implementation
Last reviewed: 2026-11-29
Caution
Authorized use only. Forged tokens, stolen-code replays and redirect tricks are shown here so you can test your own client and authorization server. Use the local Secure API lab or systems in a written scope. See LEGAL.md.
Prerequisites: API threat modeling ยท Session & token lifecycle ยท Glossary for OAuth, OIDC, JWT, PKCE
A developer reference for building OAuth 2.0 clients, authorization servers and resource servers, and OpenID Connect relying parties, to the current IETF Best Current Practice. It covers what to do, what not to do, and how to test each failure case.
Condenses RFC 9700 (OAuth 2.0 Security BCP), RFC 7636 (PKCE), OpenID Connect Core 1.0 ยง3.1.3.7 (ID token validation) and RFC 8725 (JWT BCP) into requirements, code and tests. Covers sender-constrained tokens with DPoP (RFC 9449) and mTLS (RFC 8705). The client code is from the lab's impl/fixed_api.py.
An authorization-code flow with exact redirect URIs, PKCE S256, a per-transaction state and nonce, and strict ID token validation. Tokens are audience-restricted, refresh tokens are rotated or sender-constrained, and each property has a negative test.
- Adding "Sign in with ..." or API delegation to an application
- Building or configuring an authorization server or API gateway that validates tokens
- Reviewing a JWT validation library call
- Investigating the protocol side of a token-theft finding
Note
Tenant-side consent abuse is covered elsewhere. Illicit consent grants, malicious multi-tenant apps and their investigation in Entra ID and Google Workspace are in OAuth consent & app investigation. Provider-side revocation is in token theft & session revocation. This guide covers the protocol implementation only.
- Standards Status
- Choose the Flow
- Client Requirements
- ID Token Validation
- Authorization Server Requirements
- Resource Server Requirements
- Sender-Constrained Tokens: DPoP & mTLS
- What Not to Do
- Verification Tests
| Document | Status (checked 2026-11-29) |
|---|---|
| RFC 9700 Best Current Practice for OAuth 2.0 Security | BCP 240, January 2025; updates RFC 6749, 6750 and 6819 |
| RFC 7636 PKCE | Standards Track, September 2015 |
| RFC 8725 JWT Best Current Practices | BCP 225, February 2020 |
| RFC 9449 DPoP | Standards Track, September 2023 |
| RFC 8705 OAuth mTLS | Standards Track, February 2020 |
OAuth 2.1 (draft-ietf-oauth-v2-1-17) |
Internet-Draft, not an RFC. Do not cite it as a standard |
| OAuth 2.0 for Browser-Based Applications | Published as RFC 10017 (BCP) on 2026-08-21 according to the IETF datatracker. Its text has not been reviewed for this guide |
| Situation | Use | Do not use |
|---|---|---|
| Web app with a backend | Authorization code + PKCE, confidential client | Implicit grant |
| Single-page app | Authorization code + PKCE (a backend-for-frontend keeps tokens out of the browser) | Implicit grant, tokens in localStorage
|
| Native or CLI app | Authorization code + PKCE, loopback or claimed redirect | Password grant |
| Service to service | Client credentials with private_key_jwt or mTLS client authentication |
Shared static API keys in code |
RFC 9700 ยง2.1.2: clients "SHOULD NOT use the implicit grant" or any response type that issues access tokens in the authorization response. RFC 9700 ยง2.4: the resource owner password credentials grant "MUST NOT be used". ASVS 10.4.4 asks that the authorization server only allows the grants each client needs, and says the token (implicit) and password grants "must no longer be used".
| Requirement | Source | Lab case |
|---|---|---|
| Register exact redirect URIs; the AS compares them by exact string match | RFC 9700 ยง2.1, ยง4.1.3; ASVS 10.4.1 | oauth-redirect-uri-exact-match |
CSRF protection: PKCE (once AS support is confirmed), OIDC nonce, or a one-time state bound to the user agent |
RFC 9700 ยง2.1, ยง4.7.1; ASVS 10.2.1 | oauth-state-csrf |
| "Public clients MUST use PKCE"; recommended for confidential clients | RFC 9700 ยง2.1.1 | oauth-pkce-code-injection |
| Use S256. "Currently, S256 is the only such method" that does not expose the verifier | RFC 9700 ยง2.1.1; RFC 7636 ยง4.2 | oauth-pkce-code-injection |
Mix-up defense when talking to more than one AS: the iss response parameter (RFC 9207) or distinct redirect URIs |
RFC 9700 ยง2.1, ยง4.4.2; ASVS 10.2.2 | - |
| No open redirectors on the client | RFC 9700 ยง2.1, ยง4.11 | - |
The fixed lab client creates state, nonce and the PKCE verifier per login transaction and binds them to the browser with a __Host- cookie:
tx_id = secrets.token_urlsafe(24)
verifier = secrets.token_urlsafe(48) # 64 unreserved characters (RFC 7636 4.1: 43-128)
tx = {"state": secrets.token_urlsafe(24), "nonce": secrets.token_urlsafe(24),
"verifier": verifier, "created": self.env.clock.now()}
authorization_parameters = {
"code_challenge": labcore.pkce_s256(verifier),
"code_challenge_method": "S256",
}On the callback it pops the transaction (one-time use), compares state with hmac.compare_digest, rejects transactions older than 10 minutes, and sends code_verifier with the token request.
PKCE S256 is BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) (RFC 7636 ยง4.2). This stdlib code reproduces the RFC 7636 Appendix B test vector:
import base64, hashlib, secrets
def pkce_pair() -> tuple[str, str]:
"""RFC 7636 4.1/4.2: a 43-128 character verifier and its S256 challenge."""
verifier = secrets.token_urlsafe(48) # 64 unreserved characters
digest = hashlib.sha256(verifier.encode("ascii")).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
return verifier, challenge
# RFC 7636 Appendix B test vector
v = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
c = base64.urlsafe_b64encode(hashlib.sha256(v.encode("ascii")).digest()).rstrip(b"=").decode()
assert c == "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", cOIDC Core ยง3.1.3.7 requires the client to check, among other things, that the iss claim "MUST exactly match" the issuer, that aud contains its client_id and that the token is rejected if it "contains additional audiences not trusted by the Client", that the current time is before exp, and that the nonce matches the one sent in the request. RFC 8725 ยง3.1 says libraries "MUST enable the caller to specify a supported set of algorithms". ASVS 9.1.2 asks for an algorithm allowlist.
With PyJWT 2.15.1, the validator below matches the lab's validate_id_token. It was run against RS256 tokens signed with a locally generated key. A valid token was accepted, and the forged variants were rejected with the exception shown:
import hmac
import jwt # PyJWT 2.15.1
ISSUER, CLIENT_ID = "https://idp.example.test", "client-app"
def validate_id_token(token: str, public_key_pem: bytes, expected_nonce: str) -> dict:
claims = jwt.decode(
token, public_key_pem,
algorithms=["RS256"], # never derived from the token header
audience=CLIENT_ID, issuer=ISSUER,
options={"require": ["iss", "sub", "aud", "exp", "iat"]},
)
aud = claims["aud"]
if isinstance(aud, list) and set(aud) != {CLIENT_ID}:
raise jwt.InvalidAudienceError("untrusted additional audience")
nonce = claims.get("nonce")
if not isinstance(nonce, str) or not hmac.compare_digest(nonce.encode(), expected_nonce.encode()):
raise jwt.InvalidTokenError("nonce missing or does not match")
return claims| Forged token | Observed exception (local run, Python 3.12.13) |
|---|---|
alg: none |
InvalidAlgorithmError |
Other iss
|
InvalidIssuerError |
Other aud
|
InvalidAudienceError |
aud with an extra audience |
InvalidAudienceError (raised by the list check) |
| Expired | ExpiredSignatureError |
Other nonce
|
InvalidTokenError |
Notes:
- PyJWT 2.15.1 refuses to decode without an
algorithmsargument, and refuses an RSA public key as an HMAC secret, which blocks the classic RS256-to-HS256 confusion. Keep the allowlist anyway: the protection is the explicit list, not a library default. - Get keys from the issuer's configured JWKS, never from
jku,x5uorjwkheaders in the token (RFC 8725 ยง3.10; ASVS 9.1.3).jwt.PyJWKSetparses a JWKS you have already fetched.PyJWKClientfetches over the network, so pin its URL in configuration. - OIDC Core allows TLS server validation in place of the signature for an ID token received directly from the token endpoint. The lab checks the signature anyway, as ASVS 9.1.1 asks for self-contained tokens.
- Use
sub(withiss) as the user key, never email (ASVS 10.5.2).
| Requirement | Source |
|---|---|
"Authorization servers MUST support PKCE" and enforce code_verifier when a challenge was sent |
RFC 9700 ยง2.1.1 |
Refuse a token request with code_verifier if the authorization request had no code_challenge (PKCE downgrade) |
RFC 9700 ยง2.1.1, ยง4.8.2 |
Publish code_challenge_methods_supported in metadata |
RFC 9700 ยง2.1.1 (RECOMMENDED) |
| Exact redirect URI comparison; localhost port exception for native apps only | RFC 9700 ยง4.1.3 |
| Authorization codes single-use (a second redemption is refused and tokens already issued for that code are revoked) and short-lived: up to 10 minutes at L1/L2, 1 minute at L3 | ASVS 10.4.2, 10.4.3 |
| Refresh tokens for public clients sender-constrained or rotated | RFC 9700 ยง2.2.2, ยง4.14.2; ASVS 10.4.5 |
| Refresh tokens with an absolute expiry | ASVS 10.4.8 |
Client authentication, preferably asymmetric (private_key_jwt, mTLS) |
RFC 9700 ยง2.5 |
The lab's authorization server is an in-process mock that enforces PKCE when a challenge was sent. The oauth-pkce-code-injection case shows a stolen code logging the attacker in as Bob when the client uses no PKCE, and invalid_grant when it uses S256.
- Accept only tokens meant for this API: check
aud(RFC 9700 ยง2.3; ASVS 10.3.1; RFC 9068 for JWT access tokens). - Enforce scopes and the
subfrom the token (ASVS 10.3.2, 10.3.3). - Use the RFC 6750 ยง3.1 error codes:
invalid_request(400),invalid_token(401) andinsufficient_scope(403). With no credentials at all, sendWWW-Authenticate: Bearer realm="..."without an error code. - Accept bearer tokens in the
Authorizationheader. RFC 6750 ยง2.3 says the URI query method "SHOULD NOT be used" unless the other methods are impossible, and ยง5.3 says bearer tokens should not be passed in page URLs. - For opaque tokens, the introspection endpoint must require authorization of the caller, and returns
"active": falsefor unknown or inactive tokens (RFC 7662 ยง2.1, ยง2.2).
RFC 9700 ยง2.2.1: authorization and resource servers SHOULD use sender-constraining mechanisms. ASVS 10.3.5 and 10.4.14 require them at level 3. A sender-constrained token is useless to a thief who does not also hold the client's private key.
DPoP (RFC 9449). The client sends a DPoP header holding a JWT with typ: dpop+jwt, its public key in the jwk header, and claims jti, htm, htu and iat, plus ath (the access token hash) at resource servers. The access token is then sent with the DPoP authorization scheme (ยง7.1), and the AS binds it with cnf.jkt (ยง6.1). The server checks, per ยง4.3:
- Only one
DPoPheader, holding a single well-formed JWT with all required claims -
typisdpop+jwt -
algis a registered asymmetric algorithm, notnone, and on the local allowlist - The signature verifies with the
jwkheader key, andjwkcontains no private key -
htmmatches the request method;htumatches the request URI, ignoring query and fragment -
noncematches, if the server issued one (DPoP-Nonceheader,use_dpop_nonceerror, ยง8 and ยง9) -
iat(or the nonce) is within an acceptable window, andjtihas not been seen in that window (ยง11.1) - At a resource server,
athequals the hash of the presented access token, and the token's bound key is the proof key
mTLS (RFC 8705). Client authentication methods are tls_client_auth (PKI, ยง2.1) and self_signed_tls_client_auth (ยง2.2). Certificate-bound access tokens carry cnf with x5t#S256 (ยง3.1), and the resource server compares it to the SHA-256 thumbprint of the client certificate presented on the TLS connection.
The lab does not exercise DPoP or mTLS. Treat the lists above as specification checklists, not as tested code.
| Anti-pattern | Why | Source |
|---|---|---|
| Prefix or wildcard redirect URI matching | Codes leak to look-alike hosts such as app.example.test.attacker.example.test
|
RFC 9700 ยง4.1; lab oauth-redirect-uri-exact-match
|
state that is constant, missing or not bound to the browser |
Login CSRF: the victim ends up in the attacker's account | RFC 9700 ยง4.7; lab oauth-state-csrf
|
Falling back to plain after S256 |
"Clients MUST NOT downgrade to "plain" after trying the "S256" method" | RFC 7636 ยง7.2 |
Choosing the algorithm from the token's alg header |
alg: none and HS256-with-public-key forgeries |
RFC 8725 ยง2.1, ยง3.1; lab oidc-id-token-alg-none, -alg-confusion
|
Following jku/x5u from the token |
Attacker-chosen keys and SSRF | RFC 8725 ยง3.10 |
Skipping aud or iss
|
Tokens for another client or issuer are accepted | OIDC Core ยง3.1.3.7; RFC 8725 ยง3.8, ยง3.9 |
| Decoding a JWT and trusting it | Decoding is not validation | ASVS 9.1.1 |
| Long-lived bearer refresh tokens with no rotation | A stolen token works until expiry | RFC 9700 ยง4.14 |
| Test | Expected |
|---|---|
| Redirect URI with an extra path, subdomain or suffix | AS refuses (invalid_request), no code issued |
Callback with a state from another browser, or none |
400, no session created |
Token request with a valid code but the wrong code_verifier
|
invalid_grant |
Token request with code_verifier when no challenge was sent |
invalid_grant (downgrade) |
| Same authorization code used twice | Second request refused, and tokens issued for the first redemption revoked (ASVS 10.4.2; lab case oauth-code-reuse-revokes-tokens checks the access token, and the ID token already issued, a signed JWT, cannot be recalled) |
ID tokens: alg: none, HS256 keyed with the RSA public key, wrong iss, wrong or extra aud, expired, other nonce
|
Each rejected |
| Access token for another audience at the resource server | 401 invalid_token
|
| Refresh token used twice | Second use refused; the newest token in the family is revoked too |
The lab runs the redirect, state, PKCE, code reuse, six ID token and refresh rotation tests against both twins. All passed in CI run 46241150192. That is evidence about the synthetic teaching code only.
- RFC 9700 ยท RFC 7636 ยท RFC 6749 ยท RFC 6750
- OpenID Connect Core 1.0
- RFC 8725 ยท RFC 9449 ยท RFC 8705 ยท RFC 7662
- OWASP ASVS 5.0.0: V9 Self-contained Tokens, V10 OAuth and OIDC
- PyJWT documentation
- OAuth consent & app investigation
- Token theft & session revocation
- Workload identities & GitHub OIDC
- Session & token lifecycle
- README.md - Web Application Security index
-
labs/secure-api/impl/fixed_api.py -
oauth_login,oauth_callback,validate_id_token - labs/secure-api/README.md - Lab cases and CI evidence
โฌ ๏ธ Web Application Security index | Master Index | ๐ฏ Role Navigation | Legal Notice
๐ Source: WebAppSecurity/oauth-oidc-implementation.md | โ๏ธ Suggest an edit | โฌ
๏ธ Back to Web App Security
- ๐บ๏ธ Browse by Topic
- ๐ All Repository Files
- ๐งญ Learning Paths
- ๐ Master Guide
- ๐ค Glossary
- โ๏ธ Legal & Disclaimer
๐ Foundations & Learning
๐ก๏ธ Defense & Investigations
- Incident Response
- Open Source Intelligence (OSINT)
- Reverse Engineering
- Operations Security (OPSEC)
- Compliance
โ๏ธ Platforms & Infrastructure
๐ก Hardware, Wireless & Field Projects
- PNWC Cyberdeck
- Hardware Testing
- Hardware Hacking
- Software-Defined Radio
- Wardriving
- uConsole
- Space Security
๐งฐ Assessment & Field Reference
๐ฆ Downloads & Project Resources
๐๏ธ Additional Topics