Skip to content

OAuth 2 0 and OpenID Connect Implementation

github-actions[bot] edited this page Nov 29, 2026 · 2 revisions

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

๐ŸŽฏ Purpose

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.

โš™๏ธ Function

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.

๐Ÿ† Goal

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.

๐Ÿ“‹ When To Use

  • 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.


๐Ÿ“‹ Table Of Contents

Standards Status

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

Choose the Flow

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".

Client Requirements

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", c

ID Token Validation

OIDC 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 algorithms argument, 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, x5u or jwk headers in the token (RFC 8725 ยง3.10; ASVS 9.1.3). jwt.PyJWKSet parses a JWKS you have already fetched. PyJWKClient fetches 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 (with iss) as the user key, never email (ASVS 10.5.2).

Authorization Server Requirements

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.

Resource Server Requirements

  • 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 sub from the token (ASVS 10.3.2, 10.3.3).
  • Use the RFC 6750 ยง3.1 error codes: invalid_request (400), invalid_token (401) and insufficient_scope (403). With no credentials at all, send WWW-Authenticate: Bearer realm="..." without an error code.
  • Accept bearer tokens in the Authorization header. 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": false for unknown or inactive tokens (RFC 7662 ยง2.1, ยง2.2).

Sender-Constrained Tokens: DPoP & mTLS

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:

  1. Only one DPoP header, holding a single well-formed JWT with all required claims
  2. typ is dpop+jwt
  3. alg is a registered asymmetric algorithm, not none, and on the local allowlist
  4. The signature verifies with the jwk header key, and jwk contains no private key
  5. htm matches the request method; htu matches the request URI, ignoring query and fragment
  6. nonce matches, if the server issued one (DPoP-Nonce header, use_dpop_nonce error, ยง8 and ยง9)
  7. iat (or the nonce) is within an acceptable window, and jti has not been seen in that window (ยง11.1)
  8. At a resource server, ath equals 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.

What Not to Do

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

Verification Tests

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.

๐Ÿ“š References

See also

Related Files


โฌ…๏ธ Web Application Security index | Master Index | ๐ŸŽฏ Role Navigation | Legal Notice


๐Ÿ“„ Source: WebAppSecurity/oauth-oidc-implementation.md | โœ๏ธ Suggest an edit | โฌ…๏ธ Back to Web App Security

Clone this wiki locally