PKCE (Proof Key for Code Exchange, RFC 7636, said “pixie”) is in every modern OAuth sign-in, and most developers meet it as a setting: UsePkce = true, or a library that does it without being asked. It was designed in 2015 for mobile apps, which can’t keep a client secret, and that’s still how it’s usually described. But the attack it’s best at stopping today works against web apps with secrets too, and the OAuth security best practice (RFC 9700) now recommends PKCE for every client.
This article shows what PKCE does by running the attacks it stops. A small authorization server in Node, with switches for each mistake, lets us steal a code and redeem it, inject a stolen code into another browser’s sign-in, and strip PKCE out of a request, each with PKCE off and on. Then we look at what a real server must check, using the identity provider from our BFF sample, and the mistakes clients make.
The short answer#
The problem: codes travel through the browser#
In the authorization code flow, the user signs in at the authorization server, which sends the browser back to the app’s redirect_uri with a short-lived authorization code in the URL. The app then exchanges the code for tokens in a direct, server-to-server request to the token endpoint.
The weak point is the first half. The code passes through the browser, the URL bar, redirects, and on a phone, the operating system’s handling of custom URL schemes. It can end up in browser history, proxy and server logs, a Referer header, or another app. RFC 7636 was written for the mobile case: a malicious app registers the same URL scheme as yours (com.example.app:/), and the operating system hands it your redirect, code and all. A mobile app can’t authenticate itself at the token endpoint, because any secret shipped in an app can be extracted, so whoever holds the code can redeem it.
PKCE adds a second, secret ingredient that never travels through the browser, so holding the code isn’t enough.
How PKCE works#
- 1. Appmakes a random code_verifier, keeps it, and hashes it into the code_challengestays in the app
- 2. Browser → server/authorize?…&code_challenge=…&code_challenge_method=S256front channel: visible
- 3. Serverstores the challenge with the code it issuesserver side
- 4. Server → browser → appredirect_uri?code=…front channel: can leak
- 5. App → serverPOST /token: code + code_verifier; the server checks SHA-256(verifier) = challengeback channel: direct
The client part is a few lines of Web Crypto, which runs the same in a browser and in Node:
// pkce.mjs: make a PKCE pair with Web Crypto. The same code runs in a browser and in Node.
const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
export async function challengeFor(verifier) {
const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
return base64url(new Uint8Array(hash));
}
export async function createPkce() {
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))); // 256 random bits, 43 characters
return { verifier, challenge: await challengeFor(verifier), method: "S256" };
}The verifier is 32 random bytes in base64url: 43 characters, inside the 43 to 128 that RFC 7636 allows. The challenge is the base64url of its SHA-256. Here’s a pair, and the check against the example in RFC 7636’s appendix B:
// pkce-demo.mjs: what goes where. The challenge travels through the browser; the verifier stays with the app.
import { challengeFor, createPkce } from "./pkce.mjs";
// RFC 7636, appendix B: this verifier must give this challenge.
console.log("RFC 7636 example:", (await challengeFor("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")) === "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
const { verifier, challenge } = await createPkce();
console.log(`/authorize?…&code_challenge=${challenge}&code_challenge_method=S256`);
console.log(`POST /token …&code=…&code_verifier=${verifier}`);RFC 7636 example: true
/authorize?…&code_challenge=kz1y4AT-SLSjQU6yCip8i1EKiq1QHmpvyYdg4OKLlco&code_challenge_method=S256
POST /token …&code=…&code_verifier=wUpVml8sHywZy6p73gYkglpAD7rW50aqWM5KZa8MfAsThe hash is the point. Anyone who sees the authorization request sees the challenge, but SHA-256 can’t be run backwards, so they can’t work out the verifier. And a new pair for every sign-in means each code is tied to the one sign-in that asked for it.
Attack 1: a stolen code#
To run the attacks, we need an authorization server. This one keeps codes in memory and has three switches for the mistakes we’ll test: not requiring PKCE, allowing plain, and not stopping the downgrade.
// auth-server.mjs: a minimal authorization server, with just enough to show what PKCE checks and what goes wrong without it.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
export const s256 = (verifier) => createHash("sha256").update(verifier, "ascii").digest("base64url");
export function createAuthServer({ requirePkce = true, allowPlain = false, rejectVerifierWithoutChallenge = true } = {}) {
const clients = new Map([
["mobile-app", { secret: null, redirectUri: "com.example.app:/callback" }], // public: an app can't keep a secret
["web-app", { secret: "s3cret", redirectUri: "https://app.example/callback" }], // confidential: a server-side app
]);
const codes = new Map();
// Authorization endpoint: the user has signed in and agreed, so issue a one-time code tied to this request.
function authorize({ client_id, redirect_uri, code_challenge, code_challenge_method = "plain", user }) {
const client = clients.get(client_id);
if (!client || client.redirectUri !== redirect_uri) throw new Error("invalid_request: unknown client or redirect_uri");
if (!code_challenge && requirePkce) throw new Error("invalid_request: code_challenge is required");
if (code_challenge && code_challenge_method !== "S256" && !(allowPlain && code_challenge_method === "plain"))
throw new Error("invalid_request: unsupported code_challenge_method");
const code = randomBytes(32).toString("base64url");
codes.set(code, { client_id, redirect_uri, user, code_challenge, code_challenge_method, expires: Date.now() + 60_000 });
return code;
}
// Token endpoint: the code, plus proof that the caller is the one that started this sign-in.
function token({ code, client_id, redirect_uri, client_secret, code_verifier }) {
const grant = codes.get(code);
codes.delete(code); // one use, even if this request fails
if (!grant || grant.client_id !== client_id || grant.redirect_uri !== redirect_uri || grant.expires < Date.now())
throw new Error("invalid_grant: unknown, expired or used code");
const { secret } = clients.get(client_id);
if (secret && client_secret !== secret) throw new Error("invalid_client");
if (grant.code_challenge) {
const computed = Buffer.from(grant.code_challenge_method === "S256" ? s256(code_verifier ?? "") : code_verifier ?? "");
const expected = Buffer.from(grant.code_challenge);
if (computed.length !== expected.length || !timingSafeEqual(computed, expected))
throw new Error("invalid_grant: code_verifier doesn't match the code_challenge");
} else if (code_verifier && rejectVerifierWithoutChallenge) {
throw new Error("invalid_grant: a code_verifier, but no code_challenge was sent"); // stops the downgrade (RFC 9700)
}
return { access_token: randomBytes(16).toString("base64url"), user: grant.user };
}
return { authorize, token };
}First, the case PKCE was invented for. A mobile app, a public client with no secret, signs Alice in. A malicious app gets the redirect. It knows the client_id and redirect_uri (they’re not secret), and anything in the authorization URL, including the code_challenge. It tries to redeem the code:
// interception.mjs: a public client, a mobile app with no secret. A malicious app on the same phone registered the
// same custom URL scheme and received the redirect, code and all. Can it turn the code into tokens?
import { createAuthServer } from "./auth-server.mjs";
import { createPkce } from "./pkce.mjs";
const app = { client_id: "mobile-app", redirect_uri: "com.example.app:/callback" }; // both public
function attempt(label, server, pkce) {
const challenge = pkce && { code_challenge: pkce.challenge, code_challenge_method: pkce.method };
const code = server.authorize({ ...app, ...challenge, user: "alice" });
// The attacker has the code, and anything visible in the authorization URL, including the challenge.
try {
const { user } = server.token({ ...app, code, code_verifier: pkce?.challenge });
console.log(label, `attacker has tokens for ${user}`);
} catch (e) {
console.log(label, "refused,", e.message);
}
}
const verifier = crypto.randomUUID() + crypto.randomUUID(); // 72 characters, for the plain method
attempt("no PKCE: ", createAuthServer({ requirePkce: false }));
attempt("PKCE plain: ", createAuthServer({ allowPlain: true }), { challenge: verifier, method: "plain" });
attempt("PKCE S256: ", createAuthServer(), await createPkce());no PKCE: attacker has tokens for alice
PKCE plain: attacker has tokens for alice
PKCE S256: refused, invalid_grant: code_verifier doesn't match the code_challengeWithout PKCE, the code alone is enough. With the plain method, the challenge is the verifier, so anyone who saw the authorization URL can redeem the code: plain only helps if the attacker gets the code but never sees the request, which is a narrow case. With S256, the attacker has the hash and not the verifier, and the code is refused. RFC 7636 allows plain only for clients that can’t do SHA-256, which today means none; our server rejects it unless told otherwise, and the BFF sample’s doesn’t accept it at all.
Attack 2: an injected code#
A web app with a client secret seems safe from attack 1: a stolen code is useless without the secret, and the secret is on the app’s server. So the attacker doesn’t redeem the code. They get the app to redeem it, in their session. They start a sign-in of their own, and when the authorization server would send their browser back with their code, they swap in Alice’s stolen one. The app redeems it with its own secret and signs the attacker’s browser in as Alice.
Here’s the app, with PKCE as an option:
// web-app.mjs: a confidential client, a server-side web app with a client secret, using PKCE or not.
import { createPkce } from "./pkce.mjs";
export function createWebApp(server, { usePkce }) {
const app = { client_id: "web-app", redirect_uri: "https://app.example/callback", client_secret: "s3cret" };
return {
// GET /login: keep this browser's verifier in its session, and send the browser to the authorization server.
async login(session) {
const pkce = usePkce ? await createPkce() : null;
session.verifier = pkce?.verifier;
return { client_id: app.client_id, redirect_uri: app.redirect_uri, ...(pkce && { code_challenge: pkce.challenge, code_challenge_method: "S256" }) };
},
// GET /callback?code=…: redeem the code with the secret and this session's verifier, and sign the session in.
callback(session, code) {
const { user } = server.token({ ...app, code, code_verifier: session.verifier });
delete session.verifier;
session.user = user;
},
};
}And the attack:
// injection.mjs: the attacker has a code meant for Alice (from a log, a Referer header, or a leaked redirect) and
// can't redeem it: the app has a client secret. So they paste it into their own browser's callback instead.
import { createAuthServer } from "./auth-server.mjs";
import { createWebApp } from "./web-app.mjs";
for (const usePkce of [false, true]) {
const server = createAuthServer({ requirePkce: usePkce });
const app = createWebApp(server, { usePkce });
const alice = {}, attacker = {};
const stolen = server.authorize({ ...(await app.login(alice)), user: "alice" }); // Alice signs in; her code leaks
await app.login(attacker); // the attacker starts a sign-in of their own...
try {
app.callback(attacker, stolen); // ...and swaps in Alice's code
console.log(usePkce ? "with PKCE: " : "without PKCE:", `the attacker's browser is signed in as ${attacker.user}`);
} catch (e) {
console.log(usePkce ? "with PKCE: " : "without PKCE:", "refused,", e.message);
}
}without PKCE: the attacker's browser is signed in as alice
with PKCE: refused, invalid_grant: code_verifier doesn't match the code_challengeThe client secret didn’t help at all: the app used it correctly, on the attacker’s behalf. What stops the attack is PKCE’s binding to the session. The app looks up the verifier from the attacker’s session, but Alice’s code was issued against the challenge from Alice’s session, so they don’t match. This attack is called authorization code injection, and it’s why RFC 9700 recommends PKCE for confidential clients too.
Attack 3: the downgrade#
Plenty of authorization servers support PKCE without requiring it, so older clients keep working. That leaves a gap. The attacker takes a genuine sign-in link for the app, deletes the code_challenge, and gets Alice to open it. The server issues a code with no challenge attached. Once that code leaks, the attacker injects it as before. The app sends the attacker’s verifier, and a server that only checks verifiers when a challenge exists ignores it:
// downgrade.mjs: the app always uses PKCE; the server supports it but doesn't require it. The attacker sends Alice a
// sign-in link with the code_challenge removed, gets the code it produces, and injects it as before.
import { createAuthServer } from "./auth-server.mjs";
import { createWebApp } from "./web-app.mjs";
for (const strict of [false, true]) {
const server = createAuthServer({ requirePkce: false, rejectVerifierWithoutChallenge: strict });
const app = createWebApp(server, { usePkce: true });
const attacker = {};
const { code_challenge, code_challenge_method, ...link } = await app.login({}); // a real sign-in link, minus PKCE
const stolen = server.authorize({ ...link, user: "alice" }); // Alice follows it; the code leaks
await app.login(attacker);
const label = strict ? "server checks for a challenge:" : "server ignores the verifier: ";
try {
app.callback(attacker, stolen);
console.log(label, `signed in as ${attacker.user}`);
} catch (e) {
console.log(label, "refused,", e.message);
}
}server ignores the verifier: signed in as alice
server checks for a challenge: refused, invalid_grant: a code_verifier, but no code_challenge was sentThe client did everything right, and still lost. The fix is on the server, and RFC 9700 makes it a requirement: a token request with a code_verifier must be refused if the authorization request had no code_challenge. A client that always uses PKCE always sends a verifier, so a code issued without a challenge can never be redeemed through it. The simpler fix is to require PKCE for every client, which closes the gap entirely.
What the server must check#
Most of us use an identity provider rather than write one, but these are the checks to look for in its settings and documentation. Our BFF sample includes a small identity provider in ASP.NET Core; this is its authorization endpoint, which refuses any request without an S256 challenge:
// Authorization endpoint (RFC 6749, section 4.1.1), with PKCE required (RFC 7636).
app.MapGet("/authorize", async (HttpContext http, IdpStore store, TimeProvider time) =>
{
// ...
var challenge = Get("code_challenge");
if (string.IsNullOrEmpty(challenge) || Get("code_challenge_method") != "S256")
return Fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");And its token endpoint, which takes the code (removing it, so it works once) and checks the verifier:
case "authorization_code":
{
var code = Get("code") is { } c ? store.TakeCode(c) : null;
if (code is null || code.ClientId != client.ClientId) return Error("invalid_grant", "The code is invalid, expired or already used.");
if (code.RedirectUri != Get("redirect_uri")) return Error("invalid_grant", "redirect_uri doesn't match the authorization request.");
var verifier = Get("code_verifier");
if (verifier is null || verifier.Length is < 43 or > 128) return Error("invalid_grant", "A code_verifier is required.");
var computed = Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(verifier)));
if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(computed), Encoding.ASCII.GetBytes(code.CodeChallenge)))
return Error("invalid_grant", "The code_verifier doesn't match the code_challenge.");- Require PKCE, with S256 only. If you can’t yet, at least reject a
code_verifierfor a code issued without a challenge. - Store the challenge with the code and check it against that code’s verifier, not against anything else in the request.
- Make codes single-use and short-lived (a minute is plenty), and check the
client_idandredirect_urimatch the authorization request. - Compare in constant time, as both our servers do (
timingSafeEqual,CryptographicOperations.FixedTimeEquals). - Validate the verifier’s length: 43 to 128 characters. A one-character verifier would have a guessable challenge.
- Advertise it:
code_challenge_methods_supported: ["S256"]in the discovery document, so clients know to use it.
Mistakes on the client#
- A verifier that isn’t per sign-in. Reusing one verifier across sign-ins, or across users, turns it into a shared secret, and attack 2 works again for anyone who learns it. Make a new pair every time.
- A verifier from a weak source. It must come from a cryptographic random generator; see CSPRNG vs Math.random. A verifier is a nonce of the kind that must be unpredictable, as in Nonces Explained.
- Losing the link to the session. The verifier must be found again by the same browser’s callback and only that one. A server-side app keeps it in the session (ASP.NET Core’s OpenID Connect handler keeps it in the protected state it round-trips); a single-page app keeps it in
sessionStorage, keyed bystate, so it survives the redirect. Delete it once used. - Sending the verifier through the browser. It belongs only in the back-channel token request. Putting it in a URL or the authorization request undoes the whole point.
- Writing it yourself. Use your framework’s support:
UsePkce = truein ASP.NET Core (it’s on by default), or the OAuth library your platform recommends. The client side of PKCE is small, but the session handling around it is where bugs hide.
PKCE, state and nonce#
An OpenID Connect sign-in carries three random values, and they overlap. The full comparison, with code for the nonce check, is in Nonces Explained; in short:
| Value | Checked by | Stops |
|---|---|---|
| PKCE | The authorization server, at the token endpoint | A stolen code being redeemed, or injected into another sign-in |
state | The app, on the redirect back | CSRF: a sign-in response the user didn’t start |
nonce | The app, inside the ID token | An ID token from another sign-in being injected or replayed |
RFC 9700 lets a client rely on PKCE for CSRF protection when the server supports it, and lets confidential OpenID Connect clients use the nonce instead of PKCE against code injection. Neither is a reason to drop one: send all three, as the frameworks do by default.
Who must use PKCE#
- Mobile and desktop apps: required. RFC 8252 (OAuth for native apps) says public native clients must use it.
- Browser apps: required when the browser does the OAuth itself, as RFC 10017 (OAuth for browser-based apps) describes. A backend for frontend is a confidential client, so the next point applies; our BFF sample uses PKCE anyway.
- Server-side web apps with a secret: recommended by RFC 9700, because of code injection. OAuth 2.1, still a draft, goes further and expects it from every client.
- Authorization servers: RFC 9700 says they must support PKCE, enforce it whenever a client uses it, and prevent the downgrade.
What we tested#
Every JavaScript example above is in the article’s examples file, and tests/pkce-explained/test.sh extracts them unchanged and runs them on Node 24 in Docker:
- The PKCE pair: 200 verifiers, each 43 base64url characters, with challenges equal to Node’s own SHA-256; and RFC 7636’s appendix B example.
- The normal sign-in works in all four server configurations the attacks use, for both the web app and the mobile app, and each code works once.
- The three attacks print exactly the outputs shown, five runs each.
- The C# excerpts are checked line by line against the BFF sample, and the sample’s 15 integration tests, where every sign-in uses PKCE and one checks that a request without it is refused, pass on .NET 10.
FAQ#
Does PKCE replace the client secret?
No. They prove different things. The secret proves which app is calling the token endpoint; PKCE proves it’s the same sign-in that asked for the code. A confidential client should use both. A public client has no secret, so PKCE is all it has.
Does PKCE protect against XSS in a single-page app?
No. Script injected into your page can start its own sign-in, with its own verifier, and redeem the code itself; RFC 10017 calls this acquiring new tokens, and there’s no practical way to stop it from inside a browser-only app. Keeping tokens out of the browser with a backend for frontend is the answer to that.
Does PKCE protect the tokens once they’re issued?
No. PKCE ends at the token endpoint. A stolen access or refresh token is a separate problem, handled by short lifetimes, refresh token rotation, and DPoP, which binds tokens to a key.
Why not just use the implicit flow, without a code?
The implicit flow put the access token itself in the redirect URL, with every leak described above and no way to bind it to the client. It’s deprecated: RFC 9700 says clients should not use it, and OAuth 2.1 removes it. The authorization code flow with PKCE replaced it, for browser apps too.
Can I check a code_challenge by hand?
Yes. Put the verifier into our hash generator with SHA-256 and Base64 output. The challenge is the same string in base64url: + and / become - and _, and the trailing = is dropped.
Get the code
- bff-sample on GitHub: an ASP.NET Core identity provider that requires PKCE with S256, and a BFF that uses it, with integration tests that sign in through both.
Try it in your browser
- Hash Generator: compute the SHA-256 of a code_verifier with Base64 output, and compare it with the code_challenge.
- JWT Decoder, Encoder & Editor: decode the ID and access tokens you get once the code exchange succeeds.