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.
- Author
- The RealmDeploy team
- Published
invalid_grant is the error the token endpoint returns when the grant you sent cannot buy tokens. The grant is usually an authorization code or a refresh token. The request itself is well formed, the client is known, but Keycloak refuses what is inside it.
Developers see it in two places. Right after sign-in, when the app trades the code for tokens. And minutes or hours later, when the app tries to refresh. The same error name covers more than a dozen different reasons, so the error name alone tells you little. The error_description and the realm's events tell you the rest.
This guide covers Keycloak 26.x. Every description quoted below is from the Keycloak 26.8.2 source.
What you see
The token endpoint answers HTTP 400 with a JSON body like this:
{
"error": "invalid_grant",
"error_description": "Code not valid"
}
The error_description is the useful part. These are the ones you are most likely to meet:
error_description | Where it comes from |
|---|---|
Code not valid | Code exchange: the code is unknown or was already used |
Code is expired | Code exchange: the code outlived its lifespan |
Incorrect redirect_uri | Code exchange: redirect_uri differs from the authorization request |
Session not active | Code exchange or refresh: the user session ended |
Offline session not active | Refresh with an offline token whose session timed out |
Stale token | Refresh: a newer refresh token was used, or a "not before" revocation applies |
Maximum allowed refresh token reuse exceeded | Refresh with refresh token rotation enabled |
Invalid refresh token. Token client and authorized client don't match | Refresh: the token belongs to another client |
User disabled | Code exchange or refresh: the account was disabled |
PKCE code verifier not specified | Code exchange: PKCE was used but code_verifier is missing |
Token is not active | Refresh: the refresh token is past its exp |
In the realm's events, a failed code exchange is a CODE_TO_TOKEN_ERROR event and a failed refresh is a REFRESH_TOKEN_ERROR event. The event's error field names the cause in a short code, such as invalid_code, expired_code, invalid_redirect_uri, user_session_not_found, user_disabled or code_verifier_missing.
Causes, most common first
- The code was used twice. Recognize it by
Code not validon the second of two requests. Frameworks that run the callback handler twice, a browser that retries, or a double click on a callback page all do this. Keycloak treats a second use as an attack and also detaches the client session the first use created. - The code expired.
Code is expired. Codes are meant to be traded within seconds. A breakpoint in your callback handler, a slow cold start or a queue between the callback and the token request is enough. - The
redirect_urichanged between the two requests.Incorrect redirect_uri. The token request must send exactly the sameredirect_urias the authorization request, character for character. - The user session ended.
Session not activeon refresh. The session reached SSO Session Idle or SSO Session Max, an admin signed the user out, or the user logged out in another tab. - A refresh token was used after a newer one.
Stale tokenorMaximum allowed refresh token reuse exceeded. This happens with Revoke Refresh Token turned on, when two tabs or two workers refresh at the same time. - The refresh token expired.
Token is not active. Itsexpis in the past. - The refresh token belongs to a different client.
Invalid refresh token. Token client and authorized client don't match. Two apps share a token store, or the wrong client credentials are sent. - PKCE did not line up.
PKCE code verifier not specifiedor a description that starts withPKCE verification failed:. See our guide on PKCE errors. - The user was disabled.
User disabled, on code exchange or refresh. - An offline session timed out.
Offline session not activefor tokens requested withoffline_access.
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.
CODE_TO_TOKEN_ERRORis saved by default.REFRESH_TOKEN_ERRORis not: add it to Saved types. - Reproduce the error once. Then open Events in the left menu and filter by the client. The event shows the error code, the user, the session and, for redirect mismatches, a
reasondetail. - Read the server log. The default
jboss-loggingevent listener writes failed events at WARN level. Look fortype="CODE_TO_TOKEN_ERROR"ortype="REFRESH_TOKEN_ERROR"and theerror=value on the same line. - Capture both requests. Log the full authorization URL and the token request body in your app (never the client secret). Compare
redirect_uri,client_idand the PKCE parameters between them. - Decode the refresh token. A Keycloak refresh token is a JWT. Check
exp,iat,azp(the client it was issued to),sid(the session) andtyp(RefreshorOffline). - Replay the token request with curl. Take your app out of the picture:
curl -s https://auth.example.com/realms/myrealm/protocol/openid-connect/token \
-d grant_type=refresh_token \
-d client_id=my-app \
-d client_secret="$CLIENT_SECRET" \
-d refresh_token="$REFRESH_TOKEN"
If curl works and your app does not, the problem is in how your app stores or sends the token. If curl fails the same way, the problem is the token or the realm settings.
Fixes
Code used twice
Make the callback handler idempotent. Trade the code once, store the result, and ignore a second call for the same state. In React, effects run twice in development with Strict Mode, so a token exchange inside useEffect can fire twice:
let exchanged = false;
export async function handleCallback(params) {
if (exchanged) return;
exchanged = true;
const { code, state } = params;
// check state, then exchange the code once
}
Code expired
Exchange the code as soon as the callback arrives, before any other slow work. Do not queue it. If you need a longer window while debugging, Realm settings, then the Tokens tab, holds Client Login Timeout. Raising it widens the window for a stolen code too, so set it back afterwards.
redirect_uri mismatch
Build the redirect URI once, from configuration, and use the same string in both requests:
const REDIRECT_URI = 'https://app.example.com/callback';
const authUrl = new URL(`${issuer}/protocol/openid-connect/auth`);
authUrl.searchParams.set('redirect_uri', REDIRECT_URI);
const body = new URLSearchParams({
grant_type: 'authorization_code',
code,
redirect_uri: REDIRECT_URI,
client_id: 'my-app',
code_verifier: verifier,
});
A common trap is building it from the incoming request behind a proxy, so it is http:// in one request and https:// in the other.
Session ended
This is often correct behavior: the user is signed out and must sign in again. Catch invalid_grant on refresh and send the user to the login page instead of showing an error.
Since Keycloak 26.8.0, a refresh token's exp and refresh_expires_in are capped by the user session idle timeout, and offline refresh tokens always carry exp. The upgrading guide describes it. So refresh before refresh_expires_in runs out rather than waiting for a failure. If sessions end too early for your users, review SSO Session Idle and SSO Session Max on the Sessions tab of Realm settings, and the client's own overrides on its Advanced tab.
Stale token or reuse exceeded
With Revoke Refresh Token on, each refresh token works once (or up to Refresh Token Max Reuse times). Serialize refreshes in your app so only one runs at a time, and always store the newest refresh token from the response:
let refreshing = null;
export function refresh() {
refreshing ??= doRefresh().finally(() => {
refreshing = null;
});
return refreshing;
}
If you did not mean to rotate refresh tokens, check the setting on the Tokens tab of Realm settings.
Stale token also appears when the refresh token was issued before a "not before" revocation. That is on purpose: someone pushed a revocation for the realm or the client.
Wrong client
Send the refresh token with the same client that received it. Keep one token store per client, and check azp in the decoded token against the client_id you send.
User disabled or offline session ended
Treat both like an ended session: sign the user out locally. For offline tokens, check Offline Session Idle on the Sessions tab, and whether the user still has the offline_access scope granted.
On RealmDeploy
The realm and client settings in this guide are yours, in your own admin console: session timeouts, token lifespans, Revoke Refresh Token, redirect URIs and PKCE. We do not change them for you.
User sessions are kept in the database, so a patch upgrade or a replica restart does not end them by itself. On Premium and Enterprise, more than one Keycloak replica answers requests, and that does not cause invalid_grant: every replica reads the same sessions.
If you see invalid_grant you cannot explain after these steps, write to us from the dashboard or through the contact form with the event details and the time. Our support page lists what to include.
Tools that help
- JWT decoder: paste a refresh token and read
exp,azp,sidandtyp. - JWT expiry checker: see at a glance whether a token is expired or close to it.
- OAuth error lookup: read what an
erroranderror_descriptionpair means. - Token request builder: build the code exchange request with the right parameters.
- Refresh request builder: build a refresh request as curl.
- Session timeouts: plan SSO Session Idle, SSO Session Max and client overrides together.
- Redirect URI matcher: check a redirect URI against the client's list.
- Event types reference: look up
CODE_TO_TOKEN_ERROR,REFRESH_TOKEN_ERRORand the others.
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 parameter: redirect_uri": how to fix it
Why Keycloak rejects a redirect_uri: exact and wildcard matching, http behind a proxy, post-logout URIs and the 26.7.3 rule on OIDC parameters, with fixes.