Skip to content

Blog

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_descriptionMeaning
Missing parameter: code_challenge_methodThe client requires PKCE and the request has no method
Invalid parameter: code challenge method is not matching the configured oneThe client requires one method and the request sent another
Missing parameter: code_challengeA method was sent, or PKCE is required, but there is no challenge
Invalid parameter: code_challengeThe challenge is too short, too long or has characters PKCE does not allow
Invalid parameter: code_challenge_methodThe method is neither S256 nor plain

At the token endpoint, the answer is HTTP 400 with "error": "invalid_grant" and one of these:

error_descriptionEvent error
PKCE code verifier not specifiedcode_verifier_missing
PKCE code verifier specified but challenge not present in authorizationinvalid_code_verifier
PKCE verification failed: Invalid code verifierinvalid_code_verifier
PKCE verification failed: Code mismatchpkce_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

  1. The verifier was lost between the redirect and the callback. PKCE code verifier not specified. The app stored it somewhere the callback cannot read: sessionStorage in another tab, another origin such as www. versus the bare domain, or server memory on a different instance.
  2. 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.
  3. The challenge was encoded wrongly. Also Code mismatch, or Invalid parameter: code_challenge. The app used hex, standard Base64 or kept the = padding instead of Base64url without padding.
  4. The method was left out. If the app sends a SHA-256 challenge without code_challenge_method=S256, Keycloak treats it as plain, as RFC 7636 says, and the verifier never matches. Code mismatch again.
  5. The client requires a method the app does not send. Missing parameter: code_challenge_method or the "not matching the configured one" message.
  6. The verifier has the wrong length or characters. PKCE verification failed: Invalid code verifier. RFC 7636 allows 43 to 128 characters from A-Z, a-z, 0-9 and -, ., _, ~, and Keycloak checks exactly that.
  7. 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

  1. 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.
  2. Read the event. The error code and the reason detail tell you which of the rows above you hit.
  3. 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.
  4. Log both halves. Log the code_challenge and code_challenge_method your app sends to the authorization endpoint, and the code_verifier it sends to the token endpoint, for one test sign-in. Remove the logging afterwards.
  5. 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.

  1. 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