Course contentsShow
← System Design
Lesson 923 of 1,91924. Authentication and Authorization at ScaleFree lesson

PKCE: Proof Key for Code Exchange

Protecting authorization code flows from interception attacks in public clients.

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

  1. Client generates a code verifier: A random string (43-128 characters)
  2. Client creates code challenge: Hash the verifier with SHA256, then base64url-encode it
  3. Authorization request: Send code_challenge and code_challenge_method=S256 with the auth request
  4. Authorization server stores the challenge with the issued code
  5. Token exchange: Client sends the original code_verifier (not the hash)
  6. 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.