Keycloak "Token is not active": clock skew and expiry
Why Keycloak or your API says a token is not active: expiry, clocks out of sync, short lifespans and "not before" revocations. How to check each and fix it.
- Author
- The RealmDeploy team
- Published
"Token is not active" means a token was checked at a moment outside its valid window. Either its expiry time has passed, or its not-before time has not arrived yet. The token may be perfectly signed. It is simply being used at the wrong time, or the clock that judges it is wrong.
You meet it in two places. In Keycloak itself, when an app refreshes with an expired refresh token or calls the userinfo endpoint with an expired access token. And in your own APIs, where a JWT library rejects an access token with its own wording, such as "jwt expired" or "token not yet valid". The causes are the same.
A close relative is "Stale token". Keycloak uses it for a token that was issued before a "not before" revocation, which is the deliberate way to make every older token stop working. This guide covers Keycloak 26.x, with strings quoted from the Keycloak 26.8.2 source.
What you see
On a refresh with an expired refresh token, the token endpoint answers HTTP 400:
{
"error": "invalid_grant",
"error_description": "Token is not active"
}
On the userinfo endpoint, an expired or revoked access token gets an invalid_token error with the description Token verification failed. The realm's USER_INFO_REQUEST_ERROR event holds the real reason in its reason detail, for example Token is not active or Stale token.
The token introspection endpoint does not return an error for such a token. It answers with:
{ "active": false }
A token issued before a revocation gets Stale token instead, as the error_description on refresh or as the reason on userinfo.
How Keycloak decides a token is active
Keycloak's own check is simple. A token is active when it is not expired and, if it has an nbf claim, the not-before time has been reached:
- Expiry. The token is expired when the current time is past
exp. Keycloak allows no extra time here. - Not before. Keycloak allows 10 seconds of clock difference on
nbf, so a token from a server whose clock runs slightly ahead still passes. - Revocation. Separately, a token whose
iatis before the realm's or the client's "not before" time is stale.
All times are in seconds since 1970 in UTC. Time zones never play a part, but a clock that is minutes off does.
Causes, most common first
- The token really expired. The app kept using an access token after
exp, or tried to refresh after the refresh token'sexp. Decode the token and compareexpwith the current time. - A clock is wrong. The API server, a container host or a user's laptop runs ahead or behind. Tokens look expired the moment they arrive, or not valid yet. The error appears on one machine and not on others.
- The lifespan is shorter than the app expects. The access token lives for less time than the app's refresh interval, or a client override shortens it. The gap between
iatandexptells you the lifespan. - The session ended before the refresh token's natural end. Since Keycloak 26.8.0, a refresh token's
expis capped by the user session idle timeout, so it can be shorter than you remember. See the upgrading guide. - Someone pushed a "not before" revocation.
Stale token. Every token issued before that moment stops working, on purpose. - The API has no leeway. The library rejects tokens on a difference of one second between Keycloak's clock and the API's clock.
Diagnose it step by step
- Decode the token. Read
iat,expand, if present,nbf. Write downexp - iat: that is the lifespan Keycloak gave it. - Compare with the clock of the machine that rejects it. On that machine:
date -u +%s
If iat is ahead of this number, the machine's clock is behind Keycloak's. If the token is rejected well before exp, the machine's clock is ahead.
- Check that the clock is synchronized. On a Linux host:
timedatectl status | grep -i synchronized
chronyc tracking # if the host uses chrony
Containers use the clock of the host or node they run on, so check the node, not the container.
- Compare with the time Keycloak's side reports. The
Dateheader of a response from your Keycloak hostname is a quick check:
curl -sI https://auth.example.com/realms/myrealm | grep -i '^date:'
date -u
- Look at the realm's events. In the admin console, open Realm settings, then the Events tab, and under User events settings switch on Save events.
REFRESH_TOKEN_ERRORandUSER_INFO_REQUEST_ERRORare not saved by default, so add them to Saved types. Theirreasondetail separatesToken is not activefromStale token. - Check for a revocation. Open the client in the admin console and look at Revocation on its Advanced tab. A Not Before time that is set and recent explains
Stale tokenfor that client. The realm has its own revocation setting too. - Ask Keycloak directly. Introspect the token with the API's own client credentials:
curl -s -u "my-api:$CLIENT_SECRET" \
https://auth.example.com/realms/myrealm/protocol/openid-connect/token/introspect \
-d token="$ACCESS_TOKEN"
"active": true with your library still rejecting the token points at the API's clock or its settings.
Fixes
Synchronize every clock
Run NTP on every machine that issues or checks tokens: the hosts or nodes that run Keycloak, your APIs and their nodes. With systemd:
sudo timedatectl set-ntp true
Clock problems tend to come back after a host is rebuilt or a VM is restored from a snapshot, so check again after both.
Give your API a small leeway
A small allowance for clock difference is normal. Keep it to seconds, not minutes. Some common libraries:
// jose
import { jwtVerify } from 'jose';
await jwtVerify(token, jwks, { issuer, audience, clockTolerance: 30 });
// jsonwebtoken
jwt.verify(token, key, { issuer, audience, clockTolerance: 30 });
# PyJWT
jwt.decode(token, key, algorithms=["RS256"], audience=audience, leeway=30)
// Spring Security
new JwtTimestampValidator(Duration.ofSeconds(30));
// Microsoft.IdentityModel
new TokenValidationParameters { ClockSkew = TimeSpan.FromSeconds(30) };
Spring Security's validator and Microsoft.IdentityModel already apply a default skew, so check what yours is before you add one.
Refresh before expiry, not after
Use expires_in and refresh_expires_in from the token response, not a fixed timer. Refresh shortly before the access token expires. With keycloak-js:
setInterval(async () => {
try {
await keycloak.updateToken(30);
} catch {
await keycloak.login();
}
}, 10000);
updateToken(30) refreshes when the token has less than 30 seconds left. When the refresh fails, the session is over and the user must sign in again.
Set lifespans on purpose
Access Token Lifespan is on the Tokens tab of Realm settings, and a client can override it on its Advanced tab. Short access tokens are safer, because a leaked one works only briefly. Make sure your apps refresh in time rather than raising the lifespan to hide a clock problem.
Treat Stale token as signed out
A revocation is a decision someone made. Clear the app's tokens and send the user to sign in again. If revocations surprise you, find out who set Not Before: the realm's admin events show changes made in the admin console when admin events are enabled.
APIs that check JWTs locally do not see a revocation, because the token's signature and times are still fine. If an API must honor revocations at once, it has to ask Keycloak, through introspection or userinfo, or rely on short access token lifespans.
On RealmDeploy
Lifespans, session timeouts and revocations are realm and client settings in your own admin console. The clocks of your APIs and the leeway they allow are on your side. If the Date check above shows your tenant's hostname far from the correct time, tell us: the machines your Keycloak runs on are ours.
User sessions are kept in the database, so a patch upgrade or a replica restart does not end sessions or make refresh tokens inactive by itself. Tenants run Keycloak 26.8.1, so the 26.8.0 change to refresh token expiry applies. See Keycloak versions.
If tokens from your tenant look wrong in time, send us their iat, nbf and exp values and the time you saw the error, from the dashboard or through the contact form. Never send a token itself.
Tools that help
- JWT decoder: read
iat,nbfandexpas dates. - JWT expiry checker: see where now sits between a token's time claims, against your computer's clock.
- Unix timestamp converter: turn
date -u +%soutput and claims into readable times. - JWT claims validator: check times, issuer and audience the way an API would, with a leeway.
- Introspection response viewer: read what the introspection endpoint returned.
- Refresh request builder: build a refresh request to test by hand.
- Session timeouts: plan lifespans and session timeouts together.
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_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.