What the message looks like
{"error":"invalid_grant","error_description":"Code not valid"}Common causes
- Authorization code expired (often after 30–60 seconds) or already redeemed, e.g. by a double click or browser reload.
- redirect_uri in the token request differs from the one in the authorize request.
- Refresh token expired, revoked or the IdP session ended (Keycloak: “Session not active”).
- PKCE: the code_verifier does not match the code_challenge.
- Client and IdP clocks differ significantly.
Check
- Check time synchronisation
timedatectl | grep -E 'synchronized|Local time' - Search client or IdP logs for the error
- Show the IdP's issuer and token endpoint
curl -s https://sso.example.com/realms/main/.well-known/openid-configuration | jq -r '.issuer, .token_endpoint'
Fix
- Restart the login cleanly, without the back button or a reload on the callback URL.
- Keep redirect_uri identical in app and IdP, including scheme and trailing slash.
- Sync the clock via NTP:
timedatectl set-ntp true. - For refresh errors align session lifetimes on the IdP with the app's token lifetime.
- Several app instances behind a load balancer: use shared session storage so the PKCE verifier is available on every instance.
Typical scenario
A user signs in to an application through Keycloak, is redirected back and sees only an error page. The application log says 'invalid_grant: Code not valid'. On asking, it turns out he pressed F5 on the callback page, so the authorization code was redeemed a second time. First check in the IdP's event log whether two exchange attempts are recorded for the same code, before you look at configuration or time.
FAQ
What does “Code not valid” mean in Keycloak?
The code was already redeemed, has expired or belongs to another session. Often a second callback request from a reload or prefetch is the cause.
Does the user need to do anything?
Usually a fresh login is enough. If it keeps happening, the problem is in the app, proxy or IdP configuration.
How long is an authorization code valid?
The code is short-lived and, according to the specification, may be redeemed only once. Many identity providers let it expire after about a minute or less. Repeated calls of the callback URL or slow applications therefore quickly produce an invalid_grant.
When does invalid_grant occur when renewing tokens?
Typical causes are an expired refresh token, an ended SSO session or rotation: if an already replaced refresh token is used again, some IdPs revoke the entire session. If only a new login helps, the application should trigger it cleanly.
Can a wrong redirect_uri also trigger the error?
Yes. When exchanging the code, the same redirect_uri as in the authorization request has to be sent. If it differs, many servers answer with invalid_grant rather than a more specific error. Compare both values character by character.