PKCE (Proof Key for Code Exchange)
The Cryptographic Handshake
Section titled “The Cryptographic Handshake”PKCE (Proof Key for Code Exchange) is a critical security extension for OAuth 2.0. It was originally designed for mobile apps and Single Page Applications (SPAs) but is now a “Best Current Practice” (BCP) for all OAuth clients, including server-side apps.
The PKCE Process Flow
Section titled “The PKCE Process Flow”PKCE adds a local cryptographic step before the redirect and a validation step during the token exchange.
Generate (Local)
The client creates a random `code_verifier` and its SHA-256 hash, the `code_challenge`.
Commit (Auth Request)
The client sends the `code_challenge` in the initial authorization request to the server.
Prove (Token Export)
The client sends the raw `code_verifier` during the token exchange. The server verifies it matches the previous challenge.
Security Impact: Why PKCE is Mandatory
Section titled “Security Impact: Why PKCE is Mandatory”Without PKCE, public clients (which cannot keep a secret) are vulnerable to authorization code injection and interception.
| Threat | Mitigated by PKCE? | Mechanism |
|---|---|---|
| Code Interception | Yes | Attacker lacks the code_verifier required to swap the code. |
| Man-in-the-Middle | Yes | Binds the token exchange to the specific initiation request. |
| Reverse Engineering | Yes | Challenges are unique per session; static secrets are not used. |
Implementation Reference (JavaScript)
Section titled “Implementation Reference (JavaScript)”// 1. Generate a Code Verifierconst verifier = generateRandomString(128);
// 2. Generate a Code Challenge (SHA-256)async function generateChallenge(verifier) { const encoder = new TextEncoder(); const data = encoder.encode(verifier); const digest = await window.crypto.subtle.digest('SHA-256', data);
return b64url(digest);}
// 3. Initiate Auth Requestconst authUrl = `https://auth.com/authorize?` + `response_type=code&` + `code_challenge=${await generateChallenge(verifier)}&` + `code_challenge_method=S256&...`;Related Security Patterns
Section titled “Related Security Patterns”Learn how PKCE fits into the broader secure authentication landscape.
EOF < /dev/null