PKCE binds an OAuth 2.0 authorization code to the client instance that requested it: the client sends a SHA-256 challenge with the authorize request and the original verifier with the token request, so a stolen code cannot be exchanged. Use S256, keep state for CSRF and nonce for OIDC, register exact redirect URIs, never ship a client secret, and validate ID tokens fully.
- Public clients cannot keep a secret, so PKCE replaces client authentication with proof that the same instance started and finished the flow.
- The verifier is 43-128 random characters; the challenge is its unpadded base64url SHA-256 hash, and plain is only a legacy fallback that secure servers should reject.
- state and nonce solve different problems than PKCE: state stops login CSRF, nonce stops ID token replay, and all three are required.
- Authorization codes are single-use and short-lived; a replay must fail and should revoke the tokens already issued from the first exchange.
- Validate ID tokens against the issuer's keys, issuer, audience, expiry and nonce, keep tokens out of localStorage, and rotate refresh tokens with reuse detection.
The authorization code flow is the default OAuth 2.0 grant: the client sends the user to an authorization server, receives a short-lived code on a redirect, and exchanges it for tokens on a back channel. For public clients such as browser apps, mobile apps, desktop binaries, and command-line tools, the flow is safe only with Proof Key for Code Exchange (PKCE, RFC 7636). Without PKCE, anyone who can observe the redirect can race the legitimate client to the token endpoint. This guide follows the full handshake, the parameters that matter, the validation rules that get skipped, and a checklist to run against a real deployment. The tokens returned at the end are usually JWTs; the JWT decoder shows their header and claims without pretending to verify them.
Why public clients need PKCE
RFC 6749 divides clients into confidential and public. A confidential client runs on a server the developer controls and authenticates with a client secret. A public client runs where the user can inspect and modify it, so a shipped secret is one bundle search or one decompilation away. Embedding a client secret in a single-page app or a mobile binary does not make it confidential; it only creates the illusion of protection.
The attack PKCE closes is code interception. An authorization code is a bearer credential until it is redeemed, and it travels through the address bar, browser history, referrer headers, and possibly a malicious extension. On mobile, another app can register the same custom URI scheme and receive the redirect. Without a second factor, the token endpoint sees a valid client_id, a valid code, and a matching redirect_uri, and cannot distinguish the attacker from the legitimate app.
PKCE adds that factor. The client generates a random verifier, sends only its hash as the challenge on the front channel, and presents the verifier when redeeming the code on the back channel. A stolen code without the verifier is useless. RFC 9700, the OAuth 2.0 Security Best Current Practice, requires PKCE for public clients and recommends it for confidential clients, because it also limits code injection and mix-up attacks at little cost.
PKCE is not client authentication. It does not identify the developer, and it does not replace consent, scopes, or redirect URI registration. It proves that the party redeeming the code is the same party that started the request.
Generating the code verifier and S256 challenge
RFC 7636 defines the verifier as 43 to 128 characters from the unreserved set: letters, digits, hyphen, period, underscore, and tilde. Generate it with a cryptographically secure random number generator, never with Math.random, a timestamp, or user input. Thirty-two random bytes encoded as base64url produce 43 characters and 256 bits of entropy, which is a sensible default.
The challenge is BASE64URL(SHA-256(ASCII(code_verifier))) with padding removed. The authorize request carries the challenge and code_challenge_method=S256; the token request carries the verifier. The server recomputes the hash and compares it with the stored challenge. Keep the verifier in memory or session storage keyed by state, discard it after the exchange, and never log it.
function base64url(bytes: Uint8Array): string {
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function createPkcePair(): Promise<{ verifier: string; challenge: string }> {
const random = crypto.getRandomValues(new Uint8Array(32)); // 256 bits
const verifier = base64url(random); // 43 characters, inside the 43-128 range
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
return { verifier, challenge: base64url(new Uint8Array(digest)) };
}
The plain method sets the challenge equal to the verifier. RFC 7636 permits it only when the client cannot compute SHA-256, which is rare on modern platforms; RFC 9700 tells clients to use a challenge method that does not expose the verifier, and S256 is currently the only such method. A server that accepts plain reopens the interception attack, because the verifier then travels in the front-channel URL. Treat a server that silently accepts a missing or downgraded challenge as broken rather than convenient. The Base64 tool helps check the encoding of a challenge, but the verifier itself must come from the platform's secure random source.
The authorization request and redirect URI matching
The client sends a GET request to the authorization endpoint with response_type=code, client_id, redirect_uri, scope, state, nonce for OpenID Connect, code_challenge, and code_challenge_method=S256. Percent-encode every value exactly once; the URL encoder helps verify that spaces, colons, and slashes survive. Double encoding turns the redirect URI into a different string and produces confusing invalid_request errors.
The redirect URI is the security boundary of the flow. The authorization server must compare the requested value with the registered value as an exact string: scheme, host, port, path, and query. https://app.example.com/callback does not match a trailing slash, an http scheme, or an extra query parameter. Wildcard subdomains and path-prefix matching are how attackers receive codes: control any subdomain or any path under the prefix, and the server will deliver someone else's code.
Native apps have one narrow exception. RFC 8252 allows loopback redirects on http://127.0.0.1 with a variable port, because the app cannot know the port in advance. Claimed HTTPS links, where the operating system routes a verified domain to the app, are safer than custom URI schemes, which any app on the device can register. Never put tokens, secrets, or personal data in the authorization URL; it passes through browser history, referrer headers, and proxy logs.
The token request and the code exchange
The client exchanges the code with a form-encoded POST to the token endpoint over TLS. The body contains grant_type=authorization_code, code, the same redirect_uri, client_id, and code_verifier. A public client sends no client secret and no basic authentication header. If a provider requires a secret for a browser or mobile app, it is treating a public client as confidential, and the secret is extractable.
The authorization server validates in order: the code exists, belongs to this client, has not expired, has not been redeemed, and arrived with the same redirect URI; then it hashes the verifier and compares it with the challenge in constant time. Any failure returns a single invalid_grant error without saying which check failed, so the error cannot be used as an oracle.
POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
Accept: application/json
grant_type=authorization_code
&code=SplxlOBeZQQYbYS6WxSbIA
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&client_id=web-app
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "kM4xQ2...",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMjYtMTEifQ..."
}
The response must carry Cache-Control: no-store; a cached token response is a credential leak. A common bug is sending JSON or multipart because the HTTP client defaults to it. Token endpoints parse application/x-www-form-urlencoded and may reject anything else with invalid_request. Reproduce a failing exchange byte for byte with the HTTP request workbench before changing code.
State, nonce, and login CSRF
state is an opaque, unguessable value that ties the authorization response to the browser session that started it. Store it before redirecting, compare it on the callback, and delete it after one use. Missing or mismatched state must abort the flow before any exchange. Without it, an attacker can authorize with their own account, send the victim to the callback URL, and silently log the victim into the attacker's account. That is login CSRF, and it is why state cannot be a constant or a value derived from the client_id.
nonce is an OpenID Connect parameter with a narrower job: the provider echoes the value inside the ID token, and the client compares the exact strings before accepting it. This prevents an ID token minted for another session or client from being replayed. The nonce is not a CSRF defense, and state is not a token replay defense.
PKCE replaces neither one. PKCE binds the code to the client instance, state binds the response to the user agent session, and nonce binds the ID token to the request. Keep state and verifier as a pair, and keep a map of outstanding transactions so two tabs do not overwrite each other.
Code lifetime, replay, and refresh-token security
An authorization code is single-use. RFC 6749 caps its lifetime at ten minutes. Keep it as short as the redirect flow allows; a code only needs to survive one redirect and one token request, and a lifetime near the cap is a smell. The code must be bound to the client_id and redirect URI used in the authorize request. If it is presented twice, the authorization server must reject the second exchange and should revoke the tokens issued from the first, then log the event as a possible attack. Tolerating reuse to make retries easier turns a one-time credential into a replayable one.
Refresh tokens live longer, so they need stronger handling. Rotation issues a new refresh token on every use and invalidates the old one; reuse detection revokes the whole token family and forces re-authentication when a revoked token reappears. Rotation creates a race in clients that fire several requests at once: two parallel refreshes use the same token, one succeeds, and the other receives invalid_grant, which can log the user out. Serialize refreshes behind a single-flight promise, or use a short grace window if the authorization server supports it, but do not disable rotation to hide the race.
Bearer tokens are replayable by anyone who steals them. Sender-constrained tokens change that: DPoP (RFC 9449) binds an access token to a key pair held by the client and requires a proof JWT on every request, and mutual TLS (RFC 8705) binds the token to a certificate. DPoP is the practical option when the authorization server and resource servers support it. None of this helps if the refresh token sits in localStorage, so keep it in an httpOnly Secure cookie or the operating system keychain and keep access tokens in memory.
Validating ID tokens and access tokens
An ID token is a JWT, and decoding is not validating. The JWT decoder is the right way to read the header and claims during integration, but it only proves that the token parses. A client that accepts unverified claims trusts whoever sent the token.
Validate the ID token in this order. Select the key by kid from the issuer's published JWKS and verify the signature with an algorithm allowlist; reject alg: none, reject unexpected algorithms, and do not let the token header choose an HMAC algorithm when you expect RSA. Check iss against the exact issuer string, aud for the client_id, and azp when multiple audiences are present. Check exp and iat with a clock skew allowance of at most sixty seconds. Check that nonce matches the value sent with the authorize request. Use sub as the stable user identifier and never key accounts on an email claim, which can change or be reassigned.
Access tokens need their own validation at the resource server. A JWT access token is verified like an ID token but with the resource server's audience and scope claims; an opaque token is checked by introspection (RFC 7662) or by a gateway that already did it. The token types are not interchangeable: an ID token is meant for the client and is not an API credential, and an access token is not proof of identity. Cache the JWKS by kid and refetch once on an unknown key with rate limiting; fetching the key set on every request turns a small dependency into a bottleneck.
Common mistakes that break PKCE
Most PKCE failures are not cryptographic. They are small implementation decisions that remove the protection while the flow still appears to work.
| Mistake | Why it fails | Fix |
|---|---|---|
| Shipping a client secret in a SPA or mobile app | The bundle or binary is readable, so the secret is public | Register a public client and use PKCE only |
| Wildcard or path-prefix redirect URIs | An attacker-controlled host or path receives the code | Register exact URIs and reject everything else |
| Logging codes, tokens, or verifiers | Logs become a credential store that outlives the session | Redact the fields and test the redaction |
| Missing or constant state | Login CSRF and cross-session response mixing | Random, single-use state bound to the session |
Accepting plain, a missing challenge, or a PKCE downgrade | The verifier is exposed or the challenge is bypassed entirely | Enforce S256 on both client and server |
| Storing tokens in localStorage | Any XSS bug reads and exfiltrates them | Memory for access tokens, httpOnly cookie or keychain for refresh |
| Decoding a JWT and calling it validation | Unsigned or foreign tokens are accepted | Verify signature, issuer, audience, expiry, nonce |
| Serving refresh tokens without rotation | A stolen token stays valid indefinitely | Rotate on every use and detect reuse |
The redirect row deserves emphasis. A wildcard for https://*.example.com/callback trusts every subdomain, including a marketing page or a customer-controlled tenant. A prefix match that accepts https://app.example.com/callback/anything lets an open redirect on the same host deliver the code elsewhere. Exact matching is tedious across development, staging, and production, but the alternative is a flow that looks correct in a demo and fails under attack.
Verification checklist and pass criteria
Run these checks against a staging deployment before calling the integration done. Each row has a pass condition a reviewer can reproduce.
| Check | Pass criteria | How to verify |
|---|---|---|
| Authorize request | Contains response_type=code, an S256 challenge, state, and nonce; no token in the URL | Inspect the 302 Location in the browser network panel |
| Redirect URI | Byte-identical to the registration; modified values rejected | Add a trailing slash and expect invalid_request |
| Code exchange | Succeeds once; a replay returns invalid_grant | Replay the same code with curl |
| Verifier binding | A tampered verifier fails | Change one character and expect invalid_grant |
| State binding | Missing or mismatched state aborts before exchange | Alter the state in the callback URL |
| ID token | Bad signature, issuer, audience, expiry, or nonce is rejected | Test with a token from another client and an expired token |
| No secret | No client secret in the bundle, binary, or source map | Search the build output and the packaged app |
| Token storage | No tokens in localStorage or sessionStorage; cookies are httpOnly and Secure | Inspect the Application tab and cookie flags |
| Refresh rotation | The old refresh token stops working; reuse revokes the family | Replay the previous refresh token |
| Log redaction | No codes, tokens, or verifiers in logs | Search logs for code=, eyJ, and the verifier prefix |
Two checks catch most regressions. Replay the code immediately after a successful exchange; a server that returns a second token set has failed the single-use requirement. Then open the browser storage panel after login; a token in localStorage means the next XSS is an account takeover. The JWT decoder is convenient for reading claims, but the pass criterion is that your verifier rejects a wrong aud or nonce, not that the claims look plausible.
Failure modes and debugging playbook
When the flow breaks, the error usually has one of a few recognizable shapes.
invalid_grantright after the redirect: the code expired because the callback queued the exchange, the redirect URI differs by a trailing slash or scheme, the verifier was regenerated on the callback page instead of read from storage, or a duplicate callback already redeemed the code.invalid_client: the app is registered as public but sends a secret, or the token endpoint expects a different authentication method. Remove the secret rather than adding one.invalid_request:code_challengeis missing, the method isplainand the server refuses it, or the challenge contains+,/, or=padding from a standard base64 encoder.- Login loops or state mismatch: the state cookie is blocked as cross-site without
SameSite=None; Secure, session storage was lost during a full-page redirect, or two tabs overwrote the same state slot. - ID token signature failure: the JWKS cache is stale after a key rotation, the token came from another environment, the verifier accepted the wrong algorithm, or the clock skew exceeds the allowed window.
- CORS error on the token request: the browser blocks the response because the authorization server does not allow the SPA origin. Fix CORS on the server, or move the exchange into a backend-for-frontend that keeps tokens off the browser.
Debug in this order: capture the authorize URL and confirm the challenge, state, and nonce; compare the redirect URI character by character with the registration; recompute the challenge from the stored verifier; replay the token request with curl and the exact form body; decode the ID token and check each claim. If CORS blocks the exchange and the provider will not change, a backend-for-frontend is not a workaround but the stronger design: the browser gets a session cookie, the server holds the tokens, and PKCE still protects the server-side exchange.
PKCE itself is cheap: one random string, one hash, and two extra parameters. The expensive part is the discipline around it, and the checklist separates an integration that uses PKCE from one that is actually protected by it.
Frequently asked questions
Why is PKCE required for single-page and mobile apps even though they have no client secret?
Because anyone can read a shipped JavaScript bundle or decompile an app, so a client secret provides no protection. PKCE instead binds the authorization code to a one-time verifier that never leaves the device, which stops an attacker who intercepts the redirect from exchanging the code.
Can I use code_challenge_method=plain instead of S256?
Only when the client genuinely cannot compute SHA-256, which is rare. RFC 7636 defines plain for constrained environments, but RFC 9700 tells clients to use a method that does not expose the verifier, and S256 is currently the only one. If a server accepts plain, treat it as a downgrade risk and keep the client on S256.
If I already send state, do I still need PKCE and nonce?
Yes. state protects the redirect against CSRF and login CSRF, nonce binds an OIDC ID token to the request, and PKCE binds the authorization code to the client instance. They defend different attacks, so a correct implementation uses all three.
How long can an authorization code live, and can it be reused?
An authorization code is single-use. RFC 6749 caps its lifetime at ten minutes, and you should keep it as short as the redirect flow allows. A second exchange must fail with invalid_grant, and the authorization server should revoke any tokens already issued from that code.
Should I store access and refresh tokens in localStorage?
No. Any script running on the page can read localStorage, so one cross-site scripting bug becomes full account takeover. Keep access tokens in memory, put refresh tokens in an httpOnly Secure cookie or the platform keychain, and rotate refresh tokens on every use.
JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.
Primary sources are linked at the end of each guide.