Skip to content

Blog

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_descriptionWhere it comes from
Code not validCode exchange: the code is unknown or was already used
Code is expiredCode exchange: the code outlived its lifespan
Incorrect redirect_uriCode exchange: redirect_uri differs from the authorization request
Session not activeCode exchange or refresh: the user session ended
Offline session not activeRefresh with an offline token whose session timed out
Stale tokenRefresh: a newer refresh token was used, or a "not before" revocation applies
Maximum allowed refresh token reuse exceededRefresh with refresh token rotation enabled
Invalid refresh token. Token client and authorized client don't matchRefresh: the token belongs to another client
User disabledCode exchange or refresh: the account was disabled
PKCE code verifier not specifiedCode exchange: PKCE was used but code_verifier is missing
Token is not activeRefresh: 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

  1. The code was used twice. Recognize it by Code not valid on 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.
  2. 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.
  3. The redirect_uri changed between the two requests. Incorrect redirect_uri. The token request must send exactly the same redirect_uri as the authorization request, character for character.
  4. The user session ended. Session not active on 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.
  5. A refresh token was used after a newer one. Stale token or Maximum allowed refresh token reuse exceeded. This happens with Revoke Refresh Token turned on, when two tabs or two workers refresh at the same time.
  6. The refresh token expired. Token is not active. Its exp is in the past.
  7. 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.
  8. PKCE did not line up. PKCE code verifier not specified or a description that starts with PKCE verification failed:. See our guide on PKCE errors.
  9. The user was disabled. User disabled, on code exchange or refresh.
  10. An offline session timed out. Offline session not active for tokens requested with offline_access.

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. CODE_TO_TOKEN_ERROR is saved by default. REFRESH_TOKEN_ERROR is not: add it to Saved types.
  2. 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 reason detail.
  3. Read the server log. The default jboss-logging event listener writes failed events at WARN level. Look for type="CODE_TO_TOKEN_ERROR" or type="REFRESH_TOKEN_ERROR" and the error= value on the same line.
  4. Capture both requests. Log the full authorization URL and the token request body in your app (never the client secret). Compare redirect_uri, client_id and the PKCE parameters between them.
  5. Decode the refresh token. A Keycloak refresh token is a JWT. Check exp, iat, azp (the client it was issued to), sid (the session) and typ (Refresh or Offline).
  6. 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