Skip to content

Keycloak “PKCE verification failed: Code mismatch” and “Code not valid”

Identitytested on Keycloak 26.8.1

In the authorization code flow with PKCE the application sends the code verifier it used to compute the code challenge. If it does not match, Keycloak refuses – that is what PKCE is for: an intercepted code is useless without the verifier.

Symptom

tausch falsch-falsch-falsch-falsch-falsch-falsch-falsch-1234 | jq -c .
{"error":"invalid_grant","error_description":"PKCE verification failed: Code mismatch"}

A fresh code is exchanged with a wrong verifier (falsch = “wrong”).

Diagnosis

Verifier and challenge belong together: the challenge is the base64url SHA-256 of the verifier. Both are created anew for every login.

V=$(openssl rand -base64 48 | tr -d '=+/\n' | cut -c1-64)
C=$(printf %s "$V" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
echo "${#V} ${#C}"
63 43

Causes

VerifierWrong or foreign code verifier

The application sends a different verifier than the one the request's challenge was computed from – for example after a restart or with several parallel logins.

Code not validCode already used or expired

An authorization code is valid exactly once and only briefly. The second exchange fails.

tausch "$V" | jq -c '{token_type, expires_in, scope, id_token: (.id_token != null)}'
tausch "$V" | jq -c .
{"token_type":"Bearer","expires_in":120,"scope":"openid profile email","id_token":true}
{"error":"invalid_grant","error_description":"Code not valid"}

Fix

Store the verifier together with state in the session for every login and send exactly that one in the exchange; on Code not valid start a new login and exchange the code right away.

Don't: Do not turn PKCE off because the error is annoying – without PKCE an intercepted code can be exchanged for tokens.

▶
Break it yourself and find it – free
Keycloak hands-on, Day 3: OIDC and tokens – password grant, refresh, introspection and authorization code with PKCE by hand.
Go to day 3 →

FAQ

What is state for?

state comes back unchanged; the application uses it to check that the answer belongs to its own request.

How long is an authorization code valid?

In the course one minute – the code has to be exchanged quickly.

Related error patterns

More