Authorization Code Flow with PKCE for SPAs
What you'll learn: How to implement the industry-standard OAuth 2.0 Authorization Code flow with Proof Key for Code Exchange (PKCE) to securely authenticate users in single-page applications without exposing authorization codes to attackers.
The Problem PKCE Solves
In SPAs, traditional OAuth 2.0 flows face a critical vulnerability: authorization codes can be intercepted. Since SPAs run entirely in the browser and cannot securely store client secrets, malicious apps or extensions could steal the authorization code during the redirect and exchange it for access tokens. PKCE (pronounced "pixy") eliminates this risk.
How PKCE Works
Think of PKCE like a secret handshake that only you and the authorization server know:
- Code Verifier Creation: Your SPA generates a random string called a
code_verifier(43-128 characters, cryptographically random) - Code Challenge: Hash the verifier using SHA-256, then base64url-encode it to create a
code_challenge - Authorization Request: Send the
code_challenge(not the verifier) when redirecting users to the authorization server - Authorization Code Receipt: Server returns the authorization code as usual
- Token Exchange: Send the original
code_verifierwith the authorization code to exchange for tokens
The authorization server verifies that the code_verifier hashes to the original code_challenge. Even if an attacker intercepts the authorization code, they cannot use it without the original code_verifier, which never left your SPA except during the token exchange.
Why It's Essential for SPAs
Without PKCE, any malicious app on the same device could register itself to handle the OAuth redirect and steal authorization codes. PKCE binds the authorization request to the token request cryptographically, making interception useless.
Key Takeaway: Authorization Code Flow with PKCE protects SPAs from authorization code interception by requiring proof that the app requesting tokens is the same app that initiated the authorization, using a cryptographic verifier-challenge pair that cannot be replayed by attackers.