LeepCast
Subscribe
All posts
Security

OAuth PKCE Explained: How the Authorization Code Flow Stops Stolen Codes

PKCE binds an OAuth authorization code to the client that asked for it, so an intercepted code is useless on its own. Here is how the code verifier and challenge work, what the server must enforce, and why current guidance expects PKCE from almost every client.

LeepCast7 min read

Any app that lets users sign in with an external account, or that calls an API on a user's behalf, almost certainly uses the OAuth 2.0 authorization code flow. The flow has one weak moment: the authorization code travels back to the app through a browser redirect, and anything that can read that redirect can try to redeem the code for tokens. Proof Key for Code Exchange, usually shortened to PKCE and defined in RFC 7636, closes that gap with a few lines of hashing. This guide walks through what the code is, how it gets stolen, how PKCE makes a stolen code worthless, and the checks that still matter after PKCE is in place.

The authorization code flow in one paragraph

In the flow defined by RFC 6749, the client sends the user's browser to the authorization server with response_type=code, its client_id, a redirect_uri, the requested scope, and a state value. After the user signs in and consents, the server redirects the browser back to the redirect URI with a short-lived authorization code. The client then makes a direct back-channel POST to the token endpoint with grant_type=authorization_code, the code, and the same redirect URI, and receives an access token. RFC 6749 recommends a code lifetime of at most ten minutes and requires that a code be used only once; if a code is presented twice, the server must deny the request and should revoke tokens already issued from it.

A confidential client, such as a server-side web app, also authenticates at the token endpoint with a client secret, so a thief who holds only the code cannot redeem it. A public client cannot do that. A single-page app or a mobile app ships its code to every user, so any secret embedded in it is not secret. For those clients, the code itself was effectively a bearer credential until PKCE arrived.

The attack PKCE was built for

RFC 7636 describes the original threat on mobile devices. A native app registers a custom URI scheme so the authorization server can redirect back into it. A malicious app installed on the same device registers the same scheme. When the redirect fires, the operating system may hand the URL, code included, to the malicious app, which then calls the token endpoint itself. Because a public client has no secret, the authorization server cannot tell the two apps apart.

The RFC also considers a stronger attacker who can observe the authorization request as well as the response, for example through leaked logs. That distinction matters later when choosing between the two challenge methods. Interception of the redirect is not limited to mobile, either: codes can leak through browser history, referrer headers, proxy logs, or a compromised redirect target, which is why later guidance extended PKCE to every kind of client.

How PKCE works

PKCE adds a one-time secret that the client creates for each authorization request and never sends through the browser in readable form. The exchange has three steps.

  1. The client generates a random code_verifier and derives a code_challenge from it.
  2. The client sends code_challenge and code_challenge_method with the authorization request. The server binds them to the authorization code it issues, either by storing them or by encrypting them into the code.
  3. When redeeming the code, the client sends the original code_verifier to the token endpoint. The server applies the bound method to the verifier and compares the result with the stored challenge. Tokens are issued only if they match; otherwise the server returns invalid_grant.

An attacker who intercepts the redirect gets the code but not the verifier, which never left the legitimate client. The verifier cannot be recovered from the challenge, because the challenge is a SHA-256 hash of it. A stolen code therefore cannot be redeemed.

The code verifier

RFC 7636 requires the verifier to be a high-entropy cryptographic random string between 43 and 128 characters, drawn from letters, digits, and the four characters hyphen, period, underscore, and tilde. The recommended way to build one is to take 32 random bytes and base64url-encode them without padding, which yields exactly 43 characters and 256 bits of entropy. A new verifier must be created for every authorization request; reusing one across logins defeats the purpose.

The code challenge

With the S256 method, the challenge is the base64url encoding, without padding, of the SHA-256 hash of the verifier's ASCII bytes. The plain method sets the challenge equal to the verifier. If code_challenge_method is omitted from the request, the specification defaults to plain, which is a good reason to always send S256 explicitly.

A worked example in Node. js

The script below uses only the built-in node:crypto module. It creates a verifier, derives the S256 challenge, builds an authorization URL against placeholder endpoints, and implements the comparison an authorization server performs. It ends by checking the published test vector from Appendix B of RFC 7636, so the hashing and encoding can be confirmed against the specification.

javascript
import { randomBytes, createHash, timingSafeEqual } from "node:crypto";

// Client: one fresh verifier per authorization request (32 random bytes -> 43 chars)
function createVerifier() {
  return randomBytes(32).toString("base64url");
}

// S256: BASE64URL(SHA256(ASCII(code_verifier))), no padding
function challengeFor(verifier) {
  return createHash("sha256").update(verifier, "ascii").digest("base64url");
}

// Server: recompute the challenge from the verifier and compare
function verify(verifier, storedChallenge) {
  if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(verifier)) return false;
  const a = Buffer.from(challengeFor(verifier));
  const b = Buffer.from(storedChallenge);
  return a.length === b.length && timingSafeEqual(a, b);
}

const verifier = createVerifier();
const authorizeUrl = new URL("https://auth.example.com/authorize");
authorizeUrl.search = new URLSearchParams({
  response_type: "code",
  client_id: "my-spa",
  redirect_uri: "https://app.example.com/callback",
  scope: "openid profile",
  state: randomBytes(16).toString("base64url"),
  code_challenge: challengeFor(verifier),
  code_challenge_method: "S256",
}).toString();

console.log(authorizeUrl.href);

// RFC 7636 Appendix B test vector
const rfcVerifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
console.log(challengeFor(rfcVerifier)); // E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
console.log(verify(rfcVerifier, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM")); // true
console.log(verify(createVerifier(), challengeFor(verifier))); // false

The printed URL changes on every run because the verifier and state are random, but the next three lines are fixed: the challenge for the RFC's verifier is E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, the matching verifier passes, and an unrelated verifier fails. In a real client the verifier is kept in memory or session storage until the redirect returns, then sent as code_verifier in the token request alongside grant_type, code, redirect_uri, and client_id. The constant-time comparison in the server check is a cautious default for comparing secrets rather than something the RFC mandates.

Why S256 and not plain

The plain method only helps against an attacker who sees the redirect but not the original request. If the request is observed, the challenge in it is the verifier, and the protection disappears. RFC 7636 says clients must use S256 whenever they are able to, and that plain should not appear in new implementations unless S256 is technically impossible. RFC 9700, the OAuth 2.0 Security Best Current Practice published in January 2025, adds that clients should use a method that does not expose the verifier in the authorization request and notes that S256 is currently the only such method. A client that tried S256 and got an error must not quietly retry with plain, since that is exactly what a downgrade attack would look like.

What current guidance requires

PKCE started as a fix for native apps, but RFC 9700 widened its scope. Public clients, including browser-based apps, must use PKCE. Confidential clients are recommended to use it too, because it also defends against authorization code injection, where an attacker plants a stolen code in a victim's session. Confidential OpenID Connect clients may rely on the nonce parameter instead, with care. Authorization servers must support PKCE, must enforce the verifier when a challenge was sent, and are recommended to advertise code_challenge_methods_supported in their metadata.

RFC 9700 also closes a downgrade path on the server side: a token request that contains a code_verifier must be rejected if the original authorization request carried no code_challenge. Without that rule, an attacker could start a flow without PKCE and still redeem the resulting code. Servers that simply require PKCE for every request satisfy this automatically. The OAuth 2.1 draft, still an Internet-Draft in the IETF OAuth working group at the time of writing, goes further and makes PKCE a required part of the authorization code flow.

What PKCE does not cover

PKCE protects the code exchange and nothing else. The same best-practice document lists several controls that remain necessary in a production deployment.

  • Exact redirect URI matching: authorization servers must compare redirect URIs as exact strings, with a narrow exception for the port of localhost redirects used by native apps. Pattern or prefix matching invites code theft through an attacker-controlled path.
  • CSRF protection: clients must prevent cross-site request forgery. PKCE or an OpenID Connect nonce can provide it; otherwise a one-time state value bound to the user agent is required, and state should be invalidated after first use.
  • Mix-up defense: a client that talks to more than one authorization server needs a mix-up defense, preferably the iss response parameter from RFC 9207, so a code from one server is never sent to another.
  • Refresh token protection: refresh tokens issued to public clients must be sender-constrained or rotated, so a leaked refresh token stops working.
  • Retired grants: clients should not use the implicit grant, and the resource owner password credentials grant must not be used at all.
  • Audience restriction: access tokens should be limited to the resource servers they are meant for, and resource servers must reject tokens intended for someone else.

A short implementation checklist

  • Generate a fresh 32-byte verifier from a cryptographic random source for every authorization request.
  • Always send code_challenge_method=S256 explicitly and never fall back to plain.
  • Store the verifier only on the client side of the flow, and discard it after the token request.
  • On the server, bind the challenge to the code, reject verifiers that fail the length or character rules, and return invalid_grant on mismatch.
  • Require PKCE for all clients if possible; at minimum, reject a code_verifier when no challenge was sent.
  • Keep codes single-use and short-lived, matching the RFC 6749 guidance of ten minutes or less.

PKCE is cheap to adopt: one random string, one hash, and two extra parameters. In return, the most exposed artifact in the authorization code flow stops being a usable credential on its own. Most mature OAuth libraries and identity providers already support it, so in practice the work is usually confirming it is switched on, that S256 is used, and that the server rejects requests without it.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments