Skip to main content

Keycloak Key Compromise: The Revocation Runbook

If a Keycloak realm signing key leaks, disabling that key is not enough, and setting a not-before policy is not enough either — you need both, and probably the HMAC key as well. The two levers stop different things. Disabling the RSA key removes it from the JWKS, so an access token signed by it stops verifying anywhere — but the attacker's refresh token keeps working and immediately mints a fresh one on the next key. Setting the realm's not-before policy kills every refresh token, offline token and SSO session at once — but a resource server that verifies tokens locally against the JWKS never hears about it, and keeps accepting an unexpired access token until it expires. That last gap is your real exposure window, and by default it is five minutes.

The emergency procedure, in order:

  1. Add a new RSA key provider at a higher priority. New tokens switch to it immediately.
  2. Set the realm's not-before policy to now. Refresh tokens, offline tokens and SSO sessions die.
  3. Disable (do not just make passive) the leaked provider. The old kid leaves the JWKS.
  4. Rotate the realm's HMAC key the same way if the leak was a database dump — refresh tokens, offline tokens and the SSO cookie are signed with that one, not with your RSA key.
  5. Wait out accessTokenLifespan plus your verifiers' JWKS cache. Until then, tokens already issued are still good at any resource server doing local validation.
  6. Rotate the client secrets, SMTP credentials and identity-provider secrets that were in the same dump.
Tested against

Keycloak 26.8.2 (quay.io/keycloak/keycloak:26.8.2), start-dev, on 2026-11-23. Every status, error string and HTTP code quoted below is copied from that run.

The Server Administration Guide's Compromised keys section is the official procedure and this page does not restate it. It tells you which toggles to flip; it does not say which artifacts each toggle actually stops, and its recommended "Push" step does not reach a modern resource server at all. That is the gap here.

This is the incident half of realm keys. For where the private material is stored, what the JWKS withholds, and which providers exist, read where Keycloak realm keys live first.

Set up a realm you can break​

docker rm -f kc 2>/dev/null
docker run -d --name kc --memory 1536m -p 127.0.0.1:8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:26.8.2 start-dev
alias kcadm='docker exec kc /opt/keycloak/bin/kcadm.sh'
B=http://127.0.0.1:8080/realms/rot

kcadm config credentials --server http://localhost:8080 \
--realm master --user admin --password admin

kcadm create realms -s realm=rot -s enabled=true -s sslRequired=NONE
kcadm create clients -r rot -s clientId=app -s secret=appsecret \
-s publicClient=false -s directAccessGrantsEnabled=true \
-s 'redirectUris=["http://localhost:9999/*"]'
kcadm create users -r rot -s username=alice -s enabled=true \
-s email=alice@example.com -s emailVerified=true \
-s firstName=Alice -s lastName=Example
kcadm set-password -r rot --username alice --new-password alicepw --temporary=false

Two things bite here and both cost a confusing ten minutes if you hit them cold:

  • Omit email, firstName or lastName and the password grant returns {"error":"invalid_grant","error_description":"Account is not fully set up"} — with the user's requiredActions reading as empty, which is what makes it confusing. The declarative user profile marks all three required, and a missing one raises a profile action at login time that a direct grant cannot satisfy.
  • Introspection of your own token fails with "active": false until the client is in the token's audience. Add the mapper, or every measurement below reads as "revoked" when nothing is. Details in getting the aud claim right.
CID=$(kcadm get clients -r rot -q clientId=app --fields id --format csv --noquotes)
kcadm create clients/$CID/protocol-mappers/models -r rot \
-s name=aud-app -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper \
-s 'config."included.client.audience"=app' -s 'config."access.token.claim"=true'

Get a token set to work with:

curl -s -d client_id=app -d client_secret=appsecret -d grant_type=password \
-d username=alice -d password=alicepw -d scope="openid offline_access" \
$B/protocol/openid-connect/token > /tmp/t.json

Which key signs which artifact​

This is the fact the whole runbook turns on, and nothing in the admin console shows it. Decode the headers of what you just received:

jq -r '.access_token, .refresh_token' /tmp/t.json | python3 -c '
import sys, base64
for t in sys.stdin:
h = t.strip().split(".")[0]
print(base64.urlsafe_b64decode(h + "=" * (-len(h) % 4)).decode())'
{"alg":"RS256","typ" : "JWT","kid" : "eXwV107r1I5FszoU94nRA4yoj54o4xeSrhMETSz-GQ4"}
{"alg":"HS512","typ" : "JWT","kid" : "f1cfc8d5-46da-4057-832d-41a473d0d96d"}

(Pad the base64 yourself. A JWT header is base64url with the = stripped, so piping it straight into base64 -d decodes to garbage about a third of the time, which is its own afternoon.)

Two different keys, and the second kid is the realm's HMAC key, not the RSA one in the JWKS. Repeating that across every artifact a realm emits:

ArtifactalgSigned withVerified by
Access tokenRS256realm RSA (rsa-generated)your APIs, against the JWKS
ID tokenRS256realm RSAthe client application
SAML assertionRS256the same RSA pair, published in the SAML descriptorthe SP, against a pinned certificate
Refresh tokenHS512realm HMAC (hmac-generated)Keycloak only
Offline tokenHS512realm HMACKeycloak only
KEYCLOAK_IDENTITY SSO cookieHS512realm HMACKeycloak only

The consequence is the single most surprising measurement on this page: disabling the RSA key that signed an access token does not end the session that produced it. Verified by disabling the active RSA provider and immediately refreshing a token issued under it — the old access token stops verifying, the refresh succeeds, and a new access token comes back signed by the next key in priority order. The SSO cookie is not touched either; the browser still gets silent SSO.

If you are thinking "then the key is not really what I need to revoke" — correct, and that is the point of the next section.

Six levers, and exactly what each one stops​

Each row was measured against artifacts issued before the lever was pulled.

LeverAccess token at a JWKS verifierIntrospection / /userinfoRefresh tokenOffline tokenSSO cookieNew logins
Add a higher-priority RSA provideracceptedactive: trueworksworksacceptedsigned by new key
Old RSA provider → passiveacceptedactive: trueworksworksacceptedsigned by new key
Old RSA provider → disabledrejectedactive: false / 401worksworksacceptedsigned by new key
Realm not-before (notBefore)acceptedactive: false / 401Stale tokenStale tokenrejectedwork
Sign out all sessions (logout-all)acceptedactive: false / 401Stale tokenStale tokenrejectedwork
HMAC provider → disabledacceptedactive: trueInvalid refresh tokenInvalid refresh tokenrejectedwork

Read the two bold columns against each other and the design falls out. The key levers act on signature verification: they are the only thing that reaches a resource server you do not control. The session levers act on Keycloak's own state: they are the only thing that stops a refresh token, and they are invisible to a stateless verifier. Neither is a revocation mechanism on its own.

Three details worth pinning down, because each one is a real incident waiting to happen:

Passive is not revoked. A passive key stays in the JWKS. Its status changes to PASSIVE, it stops signing new tokens, and every token it signed last week still verifies today. That is exactly what you want during a planned rotation and exactly wrong during a compromise.

"Sign out all sessions" sets the not-before policy. They are not two mechanisms. After kcadm create realms/rot/logout-all, reading the realm back shows notBefore stamped with the current epoch second, session counts at 0, and refresh attempts failing with invalid_grant / Stale token — the same error a pushed revocation policy produces, which is one of the causes listed in Keycloak invalid_grant, decoded.

The not-before policy does not touch the JWKS. An access token issued one second before the cutoff still passes local signature and exp validation, forever as far as the verifier is concerned. Introspection correctly reports active: false and /userinfo returns 401 ... error_description="Token verification failed", but an API that validates locally never asks. Which it does is a design decision you made months ago — see validating Keycloak tokens in any backend.

Why "Push" is not a revocation mechanism​

The official compromised-keys procedure ends with filling in a client's Admin URL and clicking Push. What that does today:

kcadm update clients/$CID -r rot -s adminUrl=http://localhost:9999/admin
kcadm create realms/rot/push-revocation

The command returns success. The server log says otherwise:

WARN [org.keycloak.services] KC-SERVICES0058: Failed to send revocation request:
org.apache.http.conn.HttpHostConnectException: Connect to localhost:9999 ... Connection refused

Two problems, in order of severity. The push is an HTTP POST from Keycloak to each client's Admin URL, and a failed delivery is a WARN in the server log — the admin API call that triggered it still reports success. If you treat the push as the revocation step, a firewall rule is enough to make your incident response a no-op that looks fine. And with no Admin URL set, which is the default for every client, the push does nothing at all and says nothing.

The deeper problem is who is listening. That endpoint was built for the Keycloak Java OIDC adapters, which have been removed from the project. A Spring Security resource server, Quarkus OIDC, an nginx or Envoy JWT filter, or anything else that verifies against the JWKS has no handler for it and never had one. Treat Push as a legacy convenience, and treat the notBefore value it sets as the thing that actually matters.

The planned rotation runbook​

Do this on a schedule so that the compromise runbook is something you have rehearsed.

RID=$(kcadm get realms/rot --fields id --format csv --noquotes)

# 1. Add the new signing key above the current one.
kcadm create components -r rot -s name=rsa-$(date +%Y%m) \
-s providerId=rsa-generated -s providerType=org.keycloak.keys.KeyProvider \
-s parentId=$RID -s 'config.priority=["200"]'

# 2. Confirm the active key flipped and both are published.
kcadm get keys -r rot | jq '.active.RS256'
curl -s $B/protocol/openid-connect/certs | jq -r '.keys[] | select(.use=="sig") | .kid'

Both keys now show status: ACTIVE and both are in the JWKS; the higher-priority one is the one named in the active map and the only one signing. After the overlap period, make the old provider passive, and only later disable it:

OLD=<component id of the old provider>
kcadm update components/$OLD -r rot \
-s 'config.active=["false"]' -s 'config.priority=["100"]' -s 'config.algorithm=["RS256"]'

kcadm update on a component replaces its whole config, so re-send priority and algorithm on every call or you will silently reset them.

How long the overlap needs to be is where the official advice — new keys every three to six months, delete old ones one to two months later — is more conservative than it needs to be for some realms and not conservative at all for others. Work it out from the artifacts the key actually signs:

What depends on the old RSA keyBounded byDefault on 26.8.2
Access tokens in flightaccessTokenLifespan300 s
Access tokens from the implicit flowaccessTokenLifespanForImplicitFlow900 s
Cached JWKS at your verifiersthe library's cache TTLKeycloak sends Cache-Control: no-cache; most libraries cache anyway
SAML SPs holding a pinned certificatenothing — it never expiresunbounded until you tell them
Refresh and offline tokensnothing. They are HMAC-signed.—

The last row is worth stating plainly, because the documentation says rotation "also applies to offline tokens" and on 26.8.2 with default settings it does not apply to the RSA key: an offline token issued under a key, with that key then disabled, refreshes successfully and returns a new access token on the next key. The one-to-two-month figure is the right order of magnitude for the HMAC key, whose removal invalidates every outstanding offline token with Invalid refresh token. Check offlineSessionIdleTimeout — 30 days by default, with offlineSessionMaxLifespanEnabled off — before you remove an HMAC provider.

For an OIDC-only realm with no SAML SPs, then, the honest overlap for an RSA key is the access token lifespan plus your slowest verifier's JWKS cache: minutes, not months. If you have SAML SPs, the overlap is however long it takes to get a new certificate into each of them, and the SAML descriptor publishes every enabled key, so an SP that re-reads it is fine and one that pinned the old certificate is not.

The compromise runbook​

Assume the private key is in someone else's hands. Decide one thing first: was it only the key, or a database dump? If it was a dump, the HMAC secret, the AES secret, every client secret, the SMTP password and every identity-provider secret went with it — they sit in the same table. See where realm keys live for what that table holds.

RID=$(kcadm get realms/rot --fields id --format csv --noquotes)

# 1. New signing key, highest priority. New tokens switch immediately.
kcadm create components -r rot -s name=rsa-incident \
-s providerId=rsa-generated -s providerType=org.keycloak.keys.KeyProvider \
-s parentId=$RID -s 'config.priority=["900"]'

# 2. Kill every session, refresh token and offline token in the realm.
kcadm create realms/rot/logout-all

# 3. Remove the leaked key from the JWKS. Disabled, not passive.
kcadm update components/$LEAKED -r rot \
-s 'config.enabled=["false"]' -s 'config.active=["false"]' \
-s 'config.priority=["100"]' -s 'config.algorithm=["RS256"]'

Step 2 before step 3, not after: the sessions are what let an attacker mint a new, validly signed token on your new key, and that is not something step 3 can undo. In the measured order above, a refresh attempted between the two steps still succeeds.

If it was a dump, keep going — the HMAC key is what is minting those refresh tokens:

# 4. New HMAC key, then disable the old one. This forces re-login realm-wide.
kcadm create components -r rot -s name=hmac-incident \
-s providerId=hmac-generated -s providerType=org.keycloak.keys.KeyProvider \
-s parentId=$RID -s 'config.priority=["900"]' -s 'config.algorithm=["HS512"]'

kcadm update components/$OLDHMAC -r rot \
-s 'config.enabled=["false"]' -s 'config.active=["false"]' \
-s 'config.priority=["100"]' -s 'config.algorithm=["HS512"]'

Step 4 is the destructive one. Every outstanding refresh token and offline token fails with Invalid refresh token, and every SSO cookie is rejected — a user mid-session is sent back to the login form, and a background job holding an offline token stops until someone re-consents. Do it when the leak plausibly includes the HMAC secret, and expect the support load.

Then rotate what else was in the dump: client secrets (see rotating client secrets for which client types have one), the SMTP password, and every identity-provider client secret. Nothing above touches those.

What none of this can do​

Be clear with whoever is asking for a status update:

  • You cannot retract an access token already issued. For the window between the leak and the token's exp, a resource server doing local JWKS validation will accept it, and no Keycloak setting changes that. The only way to shorten the window is to have already set a short accessTokenLifespan, or to have your APIs introspect — see session and token timeouts.
  • Disabling the key does not log anyone out. Measured above; it is the first thing people assume and it is wrong.
  • A not-before policy does not reach a verifier. It is server-side state. Introspection sees it; a JWT library does not.
  • Nothing here revokes what the attacker already did with a valid token — created clients, added a federated identity, enrolled a credential. Audit the admin events for the window, not just the keys (detecting attacks on Keycloak).

Verify it worked​

Four checks, all of which fail loudly if a step did not land:

# The leaked kid is gone from the published key set.
curl -s $B/protocol/openid-connect/certs | jq -r '.keys[].kid' | grep -q "$LEAKED_KID" \
&& echo "STILL PUBLISHED - the provider is passive, not disabled" || echo "removed"

# The realm not-before is set.
kcadm get realms/rot --fields notBefore

# A pre-incident refresh token is dead.
curl -s -d client_id=app -d client_secret=appsecret -d grant_type=refresh_token \
-d "refresh_token=$OLD_RT" $B/protocol/openid-connect/token | jq -r .error_description

# No sessions survive.
kcadm get clients/$CID/offline-session-count -r rot

Expected: removed, a non-zero notBefore, Stale token, and {"count": 0}.

Clean up: docker rm -f kc.

Named failure modes​

  • "I disabled the key and users are still getting valid tokens." They are — on your new key, through refresh tokens you did not revoke. Run logout-all.
  • "I pushed the revocation policy and nothing happened." Push posts to each client's Admin URL and logs KC-SERVICES0058 on failure while reporting success. Check the server log, and rely on the notBefore value rather than the push.
  • "Everything broke the moment I disabled the old key." Disabled removes the key from the JWKS, so every token still carrying that kid fails. In a planned rotation go passive first and wait; disabled is for incidents.
  • "Stale token on every refresh and I never set a revocation policy." Someone used Sign out all sessions, or a per-user logout, which stamps notBefore. Read it with kcadm get realms/<realm> --fields notBefore.
  • "My SAML SP broke after a routine rotation." The SP pinned the old certificate. The descriptor at /realms/<realm>/protocol/saml/descriptor publishes every enabled key; send the new one before you disable the old.
  • "The provider lost its priority after I made it passive." kcadm update on a component replaces the whole config. Re-send priority and algorithm every time.
  • "I updated the key provider and no new keys were generated." Priority changes re-rank; they never regenerate. Only a key-size change regenerates.

Next steps​