Keycloak PKCE and code_verifier errors: causes and fixes
What each Keycloak PKCE error means, from a missing code_challenge_method to "PKCE verification failed: Code mismatch", and how to find and fix the cause.
- Author
- The RealmDeploy team
- Published
PKCE (Proof Key for Code Exchange, RFC 7636) ties an authorization code to the app that asked for it. The app makes a random secret, the code verifier, and sends a hash of it, the code challenge, when it sends the user to sign in. When it trades the code for tokens, it sends the verifier itself. Keycloak hashes the verifier and checks it against the challenge it stored.
PKCE errors therefore come at two moments. At the start of sign-in, when the challenge is missing or malformed. And at the end, when the verifier is missing, malformed or does not match. The first kind comes back to your callback URL as error=invalid_request. The second comes from the token endpoint as invalid_grant.
This guide covers Keycloak 26.x. Every message quoted below is from the Keycloak 26.8.2 source.
What you see
At the authorization endpoint, Keycloak redirects back to your app with error=invalid_request and one of these error_description values:
error_description | Meaning |
|---|---|
Missing parameter: code_challenge_method | The client requires PKCE and the request has no method |
Invalid parameter: code challenge method is not matching the configured one | The client requires one method and the request sent another |
Missing parameter: code_challenge | A method was sent, or PKCE is required, but there is no challenge |
Invalid parameter: code_challenge | The challenge is too short, too long or has characters PKCE does not allow |
Invalid parameter: code_challenge_method | The method is neither S256 nor plain |
At the token endpoint, the answer is HTTP 400 with "error": "invalid_grant" and one of these:
error_description | Event error |
|---|---|
PKCE code verifier not specified | code_verifier_missing |
PKCE code verifier specified but challenge not present in authorization | invalid_code_verifier |
PKCE verification failed: Invalid code verifier | invalid_code_verifier |
PKCE verification failed: Code mismatch | pkce_verification_failed |
Token endpoint failures are CODE_TO_TOKEN_ERROR events in the realm's event log. Authorization failures are LOGIN_ERROR events with error set to invalid_request and the message in the reason detail.
Causes, most common first
- The verifier was lost between the redirect and the callback.
PKCE code verifier not specified. The app stored it somewhere the callback cannot read:sessionStoragein another tab, another origin such aswww.versus the bare domain, or server memory on a different instance. - The wrong verifier was sent.
PKCE verification failed: Code mismatch. Two sign-ins started at once, for example from two tabs, and the second overwrote the first verifier. - The challenge was encoded wrongly. Also
Code mismatch, orInvalid parameter: code_challenge. The app used hex, standard Base64 or kept the=padding instead of Base64url without padding. - The method was left out. If the app sends a SHA-256 challenge without
code_challenge_method=S256, Keycloak treats it asplain, as RFC 7636 says, and the verifier never matches.Code mismatchagain. - The client requires a method the app does not send.
Missing parameter: code_challenge_methodor the "not matching the configured one" message. - The verifier has the wrong length or characters.
PKCE verification failed: Invalid code verifier. RFC 7636 allows 43 to 128 characters fromA-Z,a-z,0-9and-,.,_,~, and Keycloak checks exactly that. - A verifier without a challenge.
PKCE code verifier specified but challenge not present in authorization. The token request sends a verifier, but the authorization request had no challenge, often because a library sends PKCE on only one of the two requests.
Diagnose it step by step
- Turn on saved events. In the admin console, open Realm settings, then the Events tab, and under User events settings switch on Save events. Then reproduce the error and open Events in the left menu.
- Read the event. The
errorcode and thereasondetail tell you which of the rows above you hit. - Check the client. Open Clients, pick the client, and look at Capability config on the Settings tab. If Require PKCE is on, PKCE Method shows the one method the client accepts.
- Log both halves. Log the
code_challengeandcode_challenge_methodyour app sends to the authorization endpoint, and thecode_verifierit sends to the token endpoint, for one test sign-in. Remove the logging afterwards. - Recompute the challenge from the logged verifier and compare:
VERIFIER='paste-the-logged-verifier-here'
printf %s "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '='
If the output differs from the challenge you sent, the encoding is wrong. If it matches, the app sent a different verifier than the one it made.
- Replay the exchange with curl, using a fresh code from a test sign-in:
curl -s https://auth.example.com/realms/myrealm/protocol/openid-connect/token \
-d grant_type=authorization_code \
-d client_id=my-spa \
-d code="$CODE" \
-d redirect_uri=https://app.example.com/callback \
-d code_verifier="$VERIFIER"
Fixes
Generate and encode correctly
Use a library when you can. If you write it yourself, this is correct in a browser:
function base64url(bytes) {
let s = '';
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export async function createPkce() {
const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
const challenge = base64url(new Uint8Array(digest));
return { verifier, challenge, method: 'S256' };
}
32 random bytes give a 43-character verifier, the shortest RFC 7636 allows. Always send code_challenge_method=S256 with the challenge.
Keep the verifier where the callback can read it
Store the verifier together with the state value, so each sign-in has its own pair:
const { verifier, challenge } = await createPkce();
const state = crypto.randomUUID();
localStorage.setItem(`pkce:${state}`, verifier);
// ...redirect with state, code_challenge and code_challenge_method=S256
// on the callback
const verifier = localStorage.getItem(`pkce:${params.get('state')}`);
localStorage.removeItem(`pkce:${params.get('state')}`);
Keying by state stops two tabs from overwriting each other. Serve the app and its callback from one origin, so www.example.com and example.com do not each keep their own storage. On a server-side app, keep the verifier in the user's server session, which every instance can read, not in process memory.
Make the client and the app agree
For public clients such as single-page and mobile apps, require PKCE with S256. In the admin console, turn on Require PKCE and choose S256 as PKCE Method. With kcadm.sh:
CID=$(kcadm.sh get clients -r myrealm -q clientId=my-spa --fields id --format csv --noquotes)
kcadm.sh update clients/$CID -r myrealm -s 'attributes."pkce.code.challenge.method"=S256'
Avoid plain. It sends the verifier itself as the challenge, so anyone who sees the authorization request has it.
If you use keycloak-js, set the method explicitly when you initialize it:
await keycloak.init({ onLoad: 'check-sso', pkceMethod: 'S256' });
Send PKCE on both requests
If a library sends a verifier but no challenge, or the other way round, fix its configuration so both requests use PKCE, or neither does. With Require PKCE on, a request without a challenge never gets a code, which surfaces the problem at the first step instead of the last.
On RealmDeploy
PKCE is a client setting in your own admin console, and the verifier lives in your app. Nothing on our side stores or changes either. Tenants run Keycloak 26.8.1 (see Keycloak versions), so the messages above are the ones you will see.
On Premium and Enterprise, several Keycloak replicas answer requests. They run as one Keycloak cluster and share sign-in state, so the authorization request and the token request may land on different replicas. That alone is not a cause of PKCE errors.
If you are stuck, write to us from the dashboard or through the contact form with the event details.
Tools that help
- PKCE generator: make a verifier and its S256 challenge, or paste a verifier and see the challenge it should produce.
- Authorization URL builder: build an authorization request with
code_challengeandcode_challenge_method. - Authorization URL inspector: check what your app really sends.
- Token request builder: build the code exchange with
code_verifieras curl. - Callback URL parser: read
erroranderror_descriptionfrom the callback. - OAuth error lookup: look up what an error means in OAuth terms.
- Base64url encoder and decoder: check an encoding by hand.
- kcadm.sh command builder: build the client update without quoting mistakes.
Keep reading
Keycloak CORS errors: causes and fixes
Why the browser blocks calls to Keycloak with a CORS error, how Web origins work, how to find the real status code behind it, and how to fix each cause.
Keycloak "HTTPS required": causes and safe fixes
What the Keycloak "HTTPS required" page means, how Require SSL decides, how to get back into a locked master realm, and why turning SSL off is the wrong fix.
Keycloak invalid_grant: causes and fixes
Why the Keycloak token endpoint answers invalid_grant: reused or expired codes, redirect_uri mismatches, ended sessions, stale refresh tokens and PKCE.