Full answer
Roles: resource owner (the user), client (the app), authorization server (issues tokens), resource server (the API).
Steps
- The client creates a random state (to tie the response to the request, prevents CSRF) and a code_verifier (43 to 128 random characters). It computes code_challenge = BASE64URL(SHA256(code_verifier)).
- It redirects the browser to /authorize with client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256.
- The user authenticates and approves. The server redirects to the exact registered redirect_uri with code and state.
- The client checks that state matches. Then it calls /token (server to server or app to server) with grant_type=authorization_code, code, redirect_uri and code_verifier.
- The server hashes the verifier, compares it with the stored challenge, checks the code is unused, unexpired and bound to this client and redirect URI, and returns the access token (and a refresh token or ID token).
What PKCE solves
- On mobile and single-page apps there is no client secret. If an attacker intercepts the code (a malicious app on the same device, a leaked log or referrer), they cannot redeem it without the verifier that never left the legitimate app.
- Servers should require S256 (not plain), keep codes valid for about a minute, and allow one use.
javascript
const crypto = require('node:crypto');
const b64url = (buf) => Buffer.from(buf).toString('base64url');
const challengeOf = (verifier) => crypto.createHash('sha256').update(verifier).digest('base64url');
// A very small authorization server.
const REGISTERED = { web: ['https://app.example.com/callback'] };
const codes = new Map();
function authorize({ client_id, redirect_uri, code_challenge, code_challenge_method, state }) {
if (!REGISTERED[client_id]?.includes(redirect_uri)) return { error: 'invalid_redirect_uri' };
if (code_challenge_method !== 'S256' || !code_challenge) return { error: 'pkce_required' };
const code = b64url(crypto.randomBytes(16));
codes.set(code, { client_id, redirect_uri, code_challenge, used: false });
return { redirect: `${redirect_uri}?code=${code}&state=${state}` };
}
function token({ client_id, redirect_uri, code, code_verifier }) {
const entry = codes.get(code);
if (!entry || entry.used || entry.client_id !== client_id || entry.redirect_uri !== redirect_uri) return { error: 'invalid_grant' };
entry.used = true; // one use only
if (!code_verifier || challengeOf(code_verifier) !== entry.code_challenge) return { error: 'invalid_grant (PKCE check failed)' };
return { access_token: 'at_' + b64url(crypto.randomBytes(8)) };
}
// The client side.
const verifier = b64url(crypto.randomBytes(32));
const state = b64url(crypto.randomBytes(8));
const request = { client_id: 'web', redirect_uri: 'https://app.example.com/callback', code_challenge: challengeOf(verifier), code_challenge_method: 'S256', state };
const params = (url) => Object.fromEntries(new URL(url).searchParams);
const reply = authorize(request);
const { code, state: returnedState } = params(reply.redirect);
console.log('verifier length :', verifier.length, '| challenge length:', request.code_challenge.length);
console.log('state matches :', returnedState === state);
console.log('attacker with stolen code:', JSON.stringify(token({ client_id: 'web', redirect_uri: request.redirect_uri, code })));
const reply2 = authorize(request);
const code2 = params(reply2.redirect).code;
console.log('app with verifier :', Object.keys(token({ client_id: 'web', redirect_uri: request.redirect_uri, code: code2, code_verifier: verifier })).join(','));
console.log('same code again :', JSON.stringify(token({ client_id: 'web', redirect_uri: request.redirect_uri, code: code2, code_verifier: verifier })));
console.log('wrong redirect_uri :', JSON.stringify(authorize({ ...request, redirect_uri: 'https://evil.example/callback' })));
console.log('no PKCE :', JSON.stringify(authorize({ ...request, code_challenge: undefined })));A toy authorization server in memory, to show the checks. A real server is an OAuth product or library, and this code is not production code. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): verifier length : 43 | challenge length: 43 state matches : true attacker with stolen code: {"error":"invalid_grant (PKCE check failed)"} app with verifier : access_token same code again : {"error":"invalid_grant"} wrong redirect_uri : {"error":"invalid_redirect_uri"} no PKCE : {"error":"pkce_required"}
Key points
- The browser carries only a short-lived code; tokens come from a back channel call.
- state links the callback to the original request.
- PKCE sends a hash of a secret first and the secret later.
- The code must be one-time and bound to client and redirect URI.
- Use PKCE for all clients.
Common mistakes
- Skipping the state check on the callback.
- Allowing wildcard or prefix redirect URIs.
- Using the implicit flow (tokens in the URL) for new apps.
- Accepting the plain PKCE method.
- Letting authorization codes be reused or live for a long time.
Follow-ups
- What is the difference between OAuth 2.0 and OpenID Connect?
- Why can a public client not keep a client secret?
- What are scopes?
Tips
- Walk through the steps in order.
- Say 'hash first, secret later'.
- Mention state and exact redirect URIs.