Implementing OAuth 2.0 PKCE for SPAs and CLIs
Generate RFC 7636 PKCE verifiers, compute S256 challenges, handle loopback redirects in CLIs, and prevent authorization code interception in browser SPAs.
On this page
Why PKCE Replaced the Implicit Flow
Public OAuth 2.0 clients—browser single-page applications (SPAs) and native command-line tools—cannot safeguard a static client_secret. Every byte shipped to a browser bundle or compiled into a CLI binary can be inspected by users or compromised extensions. Historically, SPAs leaned on the Implicit flow (response_type=token), which returned access tokens directly in the URL fragment, exposing credentials in browser history, Referer leaks, and malicious scripts. Meanwhile, desktop and CLI applications risked authorization code interception by rogue applications registering overlapping custom URI schemes.
Proof Key for Code Exchange (PKCE, specified in RFC 7636) eliminates both hazards. Instead of pre-sharing a static secret, the client invents a fresh one-time secret (code_verifier) per login attempt, sends a one-way SHA-256 commitment (code_challenge) on the front-channel redirect, and proves possession of the original code_verifier during the back-channel POST /oauth/token exchange. An attacker who intercepts the authorization code in transit cannot redeem it without knowing the preimage that never left the legitimate client’s memory or ephemeral session store.
RFC 7636 Verifier and S256 Rules
Spec compliance matters because strict identity providers (Auth0, Okta, Keycloak, GitHub, and Google) reject malformed verifiers with opaque invalid_grant errors. RFC 7636 defines a code_verifier as a high-entropy string between 43 and 128 characters drawn exclusively from the unreserved URI alphabet [A-Za-z0-9-._~]. Generating 32 cryptographically random bytes and encoding them in unpadded base64url yields exactly 43 URL-safe characters (ceil(32 * 8 / 6)), delivering 256 bits of entropy. Using 64 random bytes yields 86 characters and remains safely within the 128-character ceiling.
You can prototype and inspect compliant verifiers, S256 challenges, and complete authorization URLs directly in the Interactive PKCE Code Generator before wiring the logic into your frontend or CLI.
Browser SPA Implementation with Web Crypto
In a browser SPA, rely exclusively on window.crypto.getRandomValues and crypto.subtle.digest rather than Math.random() or external polyfills. Notice that base64url encoding differs from standard btoa output: you must swap + to -, / to _, and strip trailing = padding characters. Pair the code_verifier with an independent state nonce stored in sessionStorage so cross-site request forgery (CSRF) callbacks are rejected before hitting the token endpoint.
function toBase64Url(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
export interface PkceLoginArtifacts {
state: string;
codeVerifier: string;
codeChallenge: string;
}
export async function startPkceLogin(config: {
authorizeUrl: string;
clientId: string;
redirectUri: string;
scope: string;
}): Promise<string> {
const verifierBytes = new Uint8Array(32);
const stateBytes = new Uint8Array(24);
crypto.getRandomValues(verifierBytes);
crypto.getRandomValues(stateBytes);
const codeVerifier = toBase64Url(verifierBytes);
const state = toBase64Url(stateBytes);
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(codeVerifier),
);
const codeChallenge = toBase64Url(new Uint8Array(digest));
sessionStorage.setItem(
`pkce:${state}`,
JSON.stringify({ codeVerifier, createdAt: Date.now() }),
);
const url = new URL(config.authorizeUrl);
url.searchParams.set("response_type", "code");
url.searchParams.set("client_id", config.clientId);
url.searchParams.set("redirect_uri", config.redirectUri);
url.searchParams.set("scope", config.scope);
url.searchParams.set("state", state);
url.searchParams.set("code_challenge", codeChallenge);
url.searchParams.set("code_challenge_method", "S256");
return url.toString();
}
When the identity provider redirects back to your callback route, parse both code and state from window.location.search, check for an error query parameter first, look up pkce:${state} in sessionStorage, and remove the entry immediately before calling /oauth/token. Also enforce a short lifetime—such as ten minutes—on stored verifiers so stale browser tabs cannot replay abandoned login flows. After receiving the tokens, scrub code and state from the address bar via history.replaceState so browser extensions or analytics scripts reading location.href do not capture single-use authorization codes.
Loopback Redirects for Native CLI Tools
CLI applications cannot rely on fixed browser origins, and custom OS protocol handlers (myapp://callback) are vulnerable to scheme hijacking if another local process registers the same scheme. RFC 8252 recommends binding an ephemeral HTTP server on the loopback interface 127.0.0.1 (port 0, letting the kernel choose an unused port) for the duration of the login handshake. Avoid binding 0.0.0.0, which exposes the callback socket to other hosts on the local network.
import http from "node:http";
import crypto from "node:crypto";
function base64Url(buf: Buffer): string {
return buf.toString("base64url");
}
export async function runCliPkceCallbackServer(expectedState: string): Promise<{
redirectUri: string;
waitForCode: () => Promise<string>;
}> {
let resolveCode!: (code: string) => void;
let rejectCode!: (err: Error) => void;
const codePromise = new Promise<string>((res, rej) => {
resolveCode = res;
rejectCode = rej;
});
const server = http.createServer((req, res) => {
const reqUrl = new URL(req.url ?? "/", "http://127.0.0.1");
if (reqUrl.pathname !== "/callback") {
res.writeHead(404).end("Not found");
return;
}
const returnedState = reqUrl.searchParams.get("state");
const authError = reqUrl.searchParams.get("error");
const code = reqUrl.searchParams.get("code");
if (authError || !code || returnedState !== expectedState) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Authorization failed or state mismatch. Return to terminal.");
server.close();
rejectCode(new Error(authError ?? "Invalid state or missing authorization code"));
return;
}
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Login complete. You may close this browser tab.");
server.close();
resolveCode(code);
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("Failed to bind ephemeral loopback port");
}
const timer = setTimeout(() => {
server.close();
rejectCode(new Error("Timed out waiting for OAuth callback"));
}, 120_000);
return {
redirectUri: `http://127.0.0.1:${address.port}/callback`,
waitForCode: async () => {
try {
return await codePromise;
} finally {
clearTimeout(timer);
}
},
};
}
Notice two critical details in the Node.js snippet: crypto.randomBytes(32).toString("base64url") generates unpadded base64url natively, and the callback listener enforces a 120-second timeout so a user who closes their browser does not hang the CLI indefinitely. If the CLI runs over SSH or inside a headless container without a local browser, detect SSH_CONNECTION or DISPLAY absence early and fall back to the OAuth 2.0 Device Authorization Grant (RFC 8628) rather than silently failing when xdg-open or open exits non-zero.
Failure Modes and Security Edge Cases
Even experienced teams trip over subtle PKCE edge cases during integration:
- Accidental standard Base64 padding: Leaving
=,+, or/insidecode_challengetriggers an immediateinvalid_requestfailure on compliant authorization servers. Always strip trailing=and replace+and/before encoding query parameters. - Double URL encoding on token exchange: Submitting
application/x-www-form-urlencodedbodies via raw string interpolation risks mangling characters or leaking unencoded symbols. Always useURLSearchParamsas thefetchbody soContent-Typeand encoding match RFC 6749. - Allowing
plaindowngrades: Ensure your identity provider tenant policy explicitly disablescode_challenge_method=plain. Otherwise, a client bug that forgets to setS256silently degrades into transmitting the verifier in cleartext. - Mixing
localhostand127.0.0.1on IPv6 hosts: On macOS and Windows,localhostfrequently resolves to::1while your server listens only on127.0.0.1. Use literal127.0.0.1consistently in both the listener and the registeredredirect_uri. - Token storage in plain
localStoragevs memory: Keep short-lived access tokens in memory or behind a Backend-for-Frontend (BFF) cookie when handling sensitive operations; PKCE protects the authorization code exchange, not post-issuance XSS token theft.
Verifying Your PKCE Handshake End to End
Before shipping to staging or production, run automated verification against both positive and adversarial inputs. First, cross-check your SHA-256 base64url derivation against known test vectors from RFC 7636 Appendix B (dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk must hash to E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM) using the Interactive PKCE Code Generator. Next, write integration tests that:
- Replay the exact same
codetwice to verify the authorization server revokes or rejects duplicate redemptions. - Alter one byte of
code_verifierduring/oauth/tokenand assert HTTP400 invalid_grantis returned. - Submit a mismatched
statequery parameter to your callback handler and verify it aborts without making any outboundfetchcall to the token endpoint. - Confirm CLI loopback binding rejects requests on non-callback paths and shuts down cleanly after timeout or single successful redemption.
FAQ
- Why should public clients never use the plain code_challenge_method?
- With plain mode, code_challenge equals code_verifier verbatim, so any attacker or rogue OS URI handler observing the authorization request URL already holds the proof needed to redeem the code. Always require S256.
- Where should a browser SPA store the code_verifier during the redirect?
- Keep the verifier and state in sessionStorage keyed by the random state value and delete both immediately after reading them on callback. Avoid localStorage, which survives tab closure and widens exposure to XSS across sessions.
- Do confidential backends with a client_secret still benefit from PKCE?
- Yes. OAuth 2.1 requires PKCE even for confidential clients because PKCE binds the authorization response to the specific client instance that initiated the flow, closing authorization code injection vectors.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.