PKCE: Proof Key for Code Exchange
What you'll learn: How PKCE protects OAuth2's authorization code flow from interception attacks in public clients like mobile and single-page apps.
The Problem with Public Clients
Traditional OAuth2's authorization code flow has a vulnerability in public clients (mobile apps, SPAs) where the client secret can't be securely stored. An attacker could intercept the authorization code during the redirect and exchange it for tokens—because there's no way to verify the original requestor.
How PKCE Works
PKCE (pronounced "pixy") adds a cryptographic challenge to prove that whoever exchanges the authorization code is the same entity that initiated the flow.
The Flow
- Client generates a code verifier: A random string (43-128 characters)
- Client creates code challenge: Hash the verifier with SHA256, then base64url-encode it
- Authorization request: Send
code_challengeandcode_challenge_method=S256with the auth request - Authorization server stores the challenge with the issued code
- Token exchange: Client sends the original
code_verifier(not the hash) - Server verification: Server hashes the received verifier and compares it to the stored challenge
The Security Guarantee
Even if an attacker intercepts the authorization code, they cannot exchange it for tokens without the original code verifier—which never left the client device and wasn't transmitted during the authorization redirect.
Analogy
Think of PKCE like a claim ticket system: You generate a unique ticket (verifier) and give the coat check a hash of it (challenge). Later, you present the original ticket to claim your coat. Someone who only saw the hashed version on the receipt can't claim your coat.
Key Takeaway: PKCE makes OAuth2's authorization code flow secure for public clients by requiring proof that the token exchange request comes from the same client that initiated authorization, preventing interception attacks.