Most explanations of OAuth2 with PKCE describe the flow as a sequence diagram and stop there. The parameters that actually defend you — the code_verifier, the state value, the nonce — only make sense once you have generated them yourself and watched what happens when one is missing.
This is the authorization-code-with-PKCE flow built end to end: a public client, no client secret, an OpenID Connect provider, and the four HTTP exchanges that make it work. The authorization server here is Keycloak 26; the client is a small Node 22 script. The point is not to ship this as a library — plenty of good ones exist — but to understand what each parameter is for, so that when a library hides one or a vendor SDK gets one wrong, you can tell.
Why PKCE, and why not the implicit flow
The original OAuth2 answer for browser and mobile apps was the implicit flow: the authorization server returned the access token directly in the redirect URL fragment. It existed because a single-page application or a native app cannot keep a client secret — anything shipped to the device is readable — so there was no way to authenticate the token exchange, and the token was handed over in the redirect instead. That put a bearer token in browser history, in server logs, in the Referer header. It has been formally deprecated; the OAuth 2.0 Security Best Current Practice tells you not to use it, and OAuth 2.1 drops it entirely.
Free · 4 minutes
Would you survive contact with a determined attacker — or an auditor?
Fourteen questions on access, patching, detection, and recovery — the basics that prevent most real incidents, and the ones most often assumed rather than verified. Banded finding on screen, full sheet by email.
PKCE — Proof Key for Code Exchange, RFC 7636 — lets a public client use the authorization-code flow safely without a secret. The idea is simple. Before it starts, the client invents a random secret, the code_verifier. It sends only a hash of that secret, the code_challenge, on the initial redirect. When it later exchanges the authorization code for tokens, it presents the original code_verifier. The authorization server hashes it and checks it matches the challenge it saw at the start. An attacker who intercepts the authorization code — through a malicious app registered on the same custom URL scheme, say — cannot redeem it, because they never had the verifier.
Step one: generate the verifier and challenge
The code_verifier is a high-entropy random string, 43 to 128 characters from an unreserved-character set. The code_challenge is the base64url-encoded SHA-256 of that string — the S256 method. There is a plain method that sends the verifier unhashed; do not use it, and configure Keycloak to reject it. Base64url here means the URL-safe alphabet with the trailing = padding stripped, which is the part people get wrong.
// pkce.mjs — Node 22, no external dependencies
import { randomBytes, createHash } from 'node:crypto';
// base64url per RFC 7636: URL-safe alphabet, no padding
const base64url = (buf) =>
buf.toString('base64')
.replace(/\\+/g, '-')
.replace(/\\//g, '_')
.replace(/=+$/, '');
// 32 random bytes -> 43-character verifier, comfortably inside the 43-128 range
export const createVerifier = () => base64url(randomBytes(32));
// challenge = base64url( SHA-256( verifier ) )
export const challengeFor = (verifier) =>
base64url(createHash('sha256').update(verifier).digest());
// state and nonce are independent random values, not derived from the verifier
export const randomToken = () => base64url(randomBytes(24));
The state and nonce are separate values with separate jobs, covered below. Generate all four now and hold them — in the app’s own server-side session or, for a pure SPA, in sessionStorage keyed so a concurrent login in another tab cannot clobber it.
Step two: the /authorize redirect
You send the user’s browser to Keycloak’s authorization endpoint. For a realm named demo, that is /realms/demo/protocol/openid-connect/auth. The client must be registered in Keycloak as a public client — no secret — with the redirect URI allow-listed exactly, and with Proof Key for Code Exchange Code Challenge Method set to S256 on the client’s advanced settings so the server refuses any request without a valid challenge.
// build the authorization URL
import { createVerifier, challengeFor, randomToken } from './pkce.mjs';
const ISSUER = 'https://sso.example.com/realms/demo';
const CLIENT_ID = 'spa-client';
const REDIRECT_URI = 'https://app.example.com/callback';
const verifier = createVerifier();
const state = randomToken();
const nonce = randomToken();
// persist { verifier, state, nonce } against this browser session before redirecting
const authUrl = new URL(`${ISSUER}/protocol/openid-connect/auth`);
authUrl.search = new URLSearchParams({
response_type: 'code',
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: 'openid profile email',
state,
nonce,
code_challenge: challengeFor(verifier),
code_challenge_method: 'S256',
}).toString();
console.log(authUrl.toString()); // send the browser here
The user authenticates at Keycloak. Keycloak redirects back to REDIRECT_URI with ?code=...&state=.... The scope=openid is what makes this OpenID Connect rather than plain OAuth2 — it is the difference between getting an id_token back and not.
Step three: the checks people skip, then the /token exchange
Before you do anything with the returned code, compare the returned state against the one you stored. If it does not match, stop. This is the CSRF defence for the flow: without it, an attacker can trick a victim’s browser into completing a login the attacker started, binding the victim’s session to the attacker’s account. PKCE does not cover this — state is a separate control, and it is the one most often dropped.
Then exchange the code at the token endpoint, presenting the code_verifier. There is no client secret in this request — the verifier is what authenticates it.
// callback handler: params are the query string Keycloak redirected with
async function handleCallback(params, stored) {
if (params.get('state') !== stored.state) {
throw new Error('state mismatch — possible CSRF, aborting');
}
const res = await fetch(`${ISSUER}/protocol/openid-connect/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI, // must match the /authorize value exactly
code: params.get('code'),
code_verifier: stored.verifier, // the proof; no client_secret
}),
});
if (!res.ok) throw new Error(`token exchange failed: ${res.status}`);
return res.json(); // { access_token, id_token, refresh_token, expires_in, ... }
}
A mismatched redirect_uri, or a verifier that does not hash to the original challenge, comes back as invalid_grant. Keycloak is deliberately terse about which it was.
Step four: validate the tokens, including the nonce
Getting tokens back is not the end. The id_token is a JWT you must validate before you trust a single claim in it: verify the signature against the realm’s published JWKS at /realms/demo/protocol/openid-connect/certs; check iss equals your issuer; check aud contains your client_id; check exp has not passed. Then check the nonce claim in the token equals the nonce you generated in step one. That binds the token to this specific authentication request and defends against token replay — the OIDC counterpart to what state does for the code. Use a maintained JOSE library for the signature work rather than hand-rolling it; the validation logic is where subtle failures hide.
The access_token is for calling your APIs; the id_token is proof of who authenticated, for your client only. Do not send the id_token to a resource server as a bearer credential — a common confusion that quietly widens what a leaked token can do. If your APIs sit behind mutual TLS as well, the token is one of two independent controls; we have written separately about mutual TLS between internal services, and the two compose rather than compete.
What this buys you, and where it stops
Build the flow this way and you can account for every parameter to an auditor: PKCE protects the code in transit, state protects against CSRF on the redirect, nonce binds the ID token to the request, and token validation stops you trusting a forged or replayed assertion. Drop any one and you have a specific, nameable weakness — not a vague sense that “auth might be off”. That is the same discipline we argue for in designing the API contract before the code and in expressing controls as code: a security property you cannot point at in the request is a security property you do not have.
PKCE closes the intercepted-code hole. It does nothing about where you then store the tokens, and that is where most real breaches of these apps happen. A refresh token in localStorage is readable by any script that gets injected into your page. The flow is the easy part; the token custody after it is the part that will actually decide whether this holds.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Free interactive tool
Interactive deadline calculator
Check which regulations apply to you and when
Regulation across the EU, UK, US and Asia-Pacific has moved considerably in the past eighteen months, and several headline dates have shifted more than once. Twelve questions, about three minutes.
Results are shown on screen — no email required. A dated summary is available to download, and can be sent on if that's more useful. What we do with your answers.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.
Full Governance by Sixteen Pillars
Govern your business. Prove your compliance.
A board assurance cockpit for EU-regulated financial firms — tamper-evident, hash-chained proof of governance across DORA, GDPR, NIS2, ISO 27001, the EU AI Act and MiCA. In development.
See what's coming