Course contentsShow
← Security
Lesson 759 of 3,05216. Web Security - Authentication MechanismsFree lesson

PKCE (Proof Key for Code Exchange)

How PKCE protects authorization code flow from interception attacks, code verifier and challenge mechanics for public clients.

PKCE (Proof Key for Code Exchange)

You'll learn: How PKCE prevents attackers from intercepting authorization codes in public clients that can't keep secrets.

The Problem PKCE Solves

In OAuth 2.0's authorization code flow, public clients (mobile apps, single-page apps) can't safely store a client secret. Without PKCE, an attacker who intercepts an authorization code could exchange it for an access token—because the client can't prove it was the legitimate recipient.

PKCE fixes this by making the authorization request and token exchange cryptographically linked.

How PKCE Works

Think of PKCE like a lock-and-key system you create on the fly:

  1. Code Verifier: The client generates a random, unpredictable string (43-128 characters). This is your secret "key" that stays private on the client.

  2. Code Challenge: The client hashes the verifier (typically with SHA-256) to create a "lock." This hashed value is sent with the authorization request.

  3. Authorization Flow: The authorization server stores the code challenge alongside the authorization code.

  4. Token Exchange: When exchanging the authorization code for tokens, the client must provide the original code verifier (the "key"). The server hashes it and checks if it matches the stored challenge.

Analogy: It's like making a puzzle piece (verifier), showing someone a photo of the piece (challenge), then later proving you have the original by fitting it perfectly.

Why This Protects Against Interception

Even if an attacker intercepts the authorization code, they don't have the code verifier—it never left the client's device. Without the verifier, they can't complete the token exchange. The attacker only saw the hashed challenge, which they can't reverse.

Key Takeaway: PKCE protects public clients by requiring proof that the same entity that started the authorization flow is completing it, using a dynamically generated code verifier and challenge pair that makes intercepted authorization codes useless.