Course contentsShow
← Security
Lesson 1089 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Authorization Code Flow with PKCE for SPAs

Implementing the recommended OAuth 2.0 Authorization Code flow with Proof Key for Code Exchange to prevent authorization code interception.

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:

  1. Code Verifier Creation: Your SPA generates a random string called a code_verifier (43-128 characters, cryptographically random)
  2. Code Challenge: Hash the verifier using SHA-256, then base64url-encode it to create a code_challenge
  3. Authorization Request: Send the code_challenge (not the verifier) when redirecting users to the authorization server
  4. Authorization Code Receipt: Server returns the authorization code as usual
  5. Token Exchange: Send the original code_verifier with 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.