Key Rotation in Keycloak: Why Your Tokens Quietly Change Keys

Key Rotation in Keycloak: Why Your Tokens Quietly Change Keys

Every token Keycloak issues is signed with a cryptographic key — and that key is never meant to live forever. Here's what key rotation actually is, how Keycloak does it internally, and why it matters for every application that trusts your login screen.

Imagine a school where every exam paper is stamped with the principal’s official seal so nobody can forge a mark sheet. If the principal used the exact same seal for thirty years, and one day a copy of that seal fell into the wrong hands, every mark sheet the school ever issued — past, present, and future — would become suspect. So instead, smart schools change the seal periodically, keep the old seal valid just long enough to verify old paperwork, and quietly retire it once everything using it has expired. Keycloak’s key rotation works on exactly this principle, except the “seal” is a cryptographic key, the “mark sheets” are login tokens, and the “principal” is your identity server.

1What Is Key Rotation, Really?

Before touching Keycloak specifically, it helps to understand the general idea of a cryptographic key and why it can’t be used forever.

What is a signing key?

Every time Keycloak logs a user in, it doesn’t just say “trust me, this person is Alice.” It issues a token — a small piece of structured text — and signs it with a private cryptographic key. Anyone who receives that token can check the signature against a matching public key and be mathematically certain that only Keycloak could have created it, and that nobody tampered with it along the way. This is the same basic idea behind a bank cheque that only clears when the signature matches the one on file.

Why can’t a key be used forever?

A signing key is a secret. The moment it is created, several clocks start ticking against it: the algorithm it uses may weaken over time as computers get faster, the key file could leak through a misconfigured backup or a compromised server, and simply keeping any secret unchanged for years increases the chance it has already been copied without your knowledge. Security engineering treats “how long has this secret existed” as a risk factor in its own right, independent of whether you have evidence of a leak.

Simple Analogy

Think of a signing key like the lock on your front door. Even if nothing has gone wrong, a locksmith will tell you to re-key the lock every few years — not because you know a burglar has a copy, but because you can never be fully sure who might have quietly made one. Key rotation is Keycloak re-keying its own front door on a schedule, instead of waiting for a break-in to prove the old lock was bad.

So what is “rotation” specifically?

Key rotation is the practice of periodically retiring an old signing key and replacing it with a fresh one, while making sure nothing breaks in the process. The tricky part is that word “nothing” — thousands of tokens signed with the old key may still be circulating and need to keep working until they naturally expire. Rotation is not simply “delete old key, create new key”; it is a carefully staged handover.

i
Key Point

Rotation is not the same as revocation. Revocation is an emergency reaction to a known compromise. Rotation is routine, scheduled maintenance that happens whether or not anything went wrong — much like changing engine oil on a schedule rather than waiting for the engine to fail.

2Architecture: Where Keys Live Inside Keycloak

Keycloak does not treat keys as a special, separate concept — it treats them as ordinary configuration pieces called “components,” which is central to understanding how rotation works.

Realms and realm keys

In Keycloak, every realm — the isolated space that holds a group of users, clients, and roles, similar to a separate tenant — owns its own set of signing keys. A key that belongs to the “customers” realm has nothing to do with the key that belongs to the “employees” realm on the same server. This means rotation is always a per-realm decision.

Key providers

Under the hood, Keycloak stores each key as something called a key provider component. A provider bundles together the actual key material, the algorithm it uses, and a set of flags that control its behavior. Multiple providers can exist side by side in the same realm at the same time — which is exactly what makes a smooth rotation possible.

Component

Provider ID

Identifies the kind of key: for example rsa for a standard RSA signing keypair, or rsa-enc for a keypair used for encryption rather than signing.

Component

Algorithm

The cryptographic scheme, such as RS256 (RSA with SHA-256) or the elliptic-curve and PS-family variants Keycloak also supports.

Component

Priority

A number that decides which active key Keycloak actually signs new tokens with, out of all the keys present.

Component

Active / Enabled Flags

Two independent switches: “enabled” controls whether the key can be used at all, and “active” controls whether it can be used for new signatures versus only for verifying old ones.

Managed keys vs. custom keys

By default, Keycloak automatically generates and manages a key for you the moment a realm is created — this is called a managed key. Administrators can also bring their own keypair, generated externally or issued by a corporate certificate authority, and register it as a custom key. Both types behave identically once registered: they carry the same priority, active, and enabled properties, and Keycloak treats them the same way when deciding what to sign with.

Simple Analogy

Think of the realm as an office with a key cabinet. Each key on the wall is labelled with a priority number. The office manager (Keycloak) always grabs the highest-priority key that is still marked “usable for new documents.” Older keys stay on the wall, still able to open the drawers they were made for, until everyone agrees they’re no longer needed.

3Internal Working: How Keycloak Picks a Key

This is the mechanical heart of rotation — the rule Keycloak follows every single time it needs to sign or verify something.

Signing a new token

Whenever Keycloak needs to sign a brand-new token — an access token, an ID token, or a SAML assertion — it looks across every key provider registered for that realm, filters down to the ones marked both enabled and active, and picks the single one with the highest priority number. That key, and only that key, is used to produce the signature. If two keys tie on priority, Keycloak breaks the tie using its own internal ordering, but in practice administrators are expected to give every key a distinct priority to avoid ambiguity.

The “kid” — how a verifier knows which key was used

Every token Keycloak signs carries a small header field called kid, short for “key ID.” This is effectively a fingerprint that says “I was signed with key number X.” A verifying application doesn’t need to guess which key to check against — it reads the kid, looks that specific key up, and validates the signature against exactly that one. This single detail is what makes rotation possible without breaking existing tokens: old tokens simply point back to their old key by ID.

sequenceDiagram
    autonumber
    participant U as User Login
    participant KC as Keycloak
    participant APP as Client Application
    U->>KC: Authenticates
    KC->>KC: Select highest-priority ACTIVE key
    KC-->>U: Signed token (includes kid)
    U->>APP: Sends token
    APP->>KC: Fetches /certs (JWKS) using kid
    KC-->>APP: Matching public key
    APP->>APP: Verifies signature locally
        
FIG 1 — How a token’s “kid” links it back to the exact key that signed it

The public certs endpoint (JWKS)

Applications never see Keycloak’s private keys. Instead, each realm exposes a public endpoint — commonly the realm’s /protocol/openid-connect/certs path — that publishes every enabled public key as a JSON Web Key Set (JWKS). Client libraries fetch this list, usually caching it for some minutes, and use it to verify signatures locally without calling Keycloak on every single request. When a key rotates, this published list changes to include the new key while, crucially, still listing the old one for as long as it remains enabled.

!
Common Misconception

Rotating a key does not mean instantly deleting the old one from this public list. If it disappeared immediately, every token still in circulation that was signed with it would suddenly fail verification. The old key stays published — just disabled for new signing — until it is safe to remove.

4Data Flow & Lifecycle of a Key

A key doesn’t just switch from “new” to “gone.” It moves through clearly defined stages, and understanding these stages is the whole game when planning a rotation.

1

Created

A new key provider is added to the realm, either auto-generated by Keycloak or supplied by an administrator, typically at a lower priority than the current key so it doesn’t take over immediately.

2

Promoted to Active

The administrator raises its priority above the existing key (or flips its active flag). From this moment, every newly issued token is signed with the new key.

3

Old Key Becomes Passive

The previous key is no longer used to sign anything new, but it remains enabled. It stays fully able to verify any token that was already signed with it, and it stays listed in the public JWKS endpoint.

4

Grace Period

The old key sits in this passive-but-enabled state for a deliberate window of time — long enough that every token signed under it has naturally expired. This window is the single most important number in the whole rotation process.

5

Disabled and Removed

Once the grace period has safely passed, the old key can be disabled and eventually deleted from the realm entirely, closing the loop.

Why the grace period matters more than the rotation itself

Most rotation mistakes are not caused by generating the new key wrongly — they’re caused by removing the old key too soon. If a token was issued with a 30-minute lifetime but also came with a long-lived refresh token, and the signing key that produced it is deleted after only 10 minutes, every application relying on that token or its downstream artifacts breaks instantly and unpredictably. The grace period must be sized against the longest-lived artifact that could reference the old key, not just the shortest one.

“A rotation isn’t finished when the new key starts signing tokens — it’s finished when the old key has nothing left to verify.”

5Advantages and Trade-offs

Rotation isn’t free — it trades a small amount of operational complexity for a large amount of long-term safety.

Advantages

  • Limits how much damage a single leaked key can do, since it will naturally stop being trusted for new tokens even if the leak is never detected.
  • Lets an organization upgrade to stronger algorithms or larger key sizes over time without a hard cutover.
  • Supports compliance requirements common in banking, healthcare, and government contracts that mandate periodic credential rotation.
  • Makes emergency key replacement (after a confirmed breach) a well-rehearsed, low-drama procedure instead of a first-time panic.
  • Keeps the “blast radius” of any future compromise limited to whatever window of tokens the current key has signed.

Disadvantages / Trade-offs

  • Adds operational steps: someone has to create, promote, and eventually retire keys on a schedule.
  • A rotation performed with too short a grace period can cause a wave of confusing authentication failures.
  • Client applications that cache the public key list too aggressively, or that hardcode a single key instead of reading the “kid,” can silently break during rotation.
  • Custom (externally supplied) keys add coordination overhead, since the external certificate authority’s renewal schedule now has to line up with Keycloak’s rotation schedule.

6Security Considerations

Rotation is itself a security control, but it interacts with several other security concerns that are worth understanding together.

Algorithm strength and key size

Rotation is the natural opportunity to move from a weaker algorithm or a smaller key size to a stronger one, without ever needing a “big bang” migration. For example, an organization on 2048-bit RSA keys can introduce a 4096-bit or elliptic-curve replacement as the next rotation cycle’s key, and the transition happens exactly as smoothly as any other rotation.

Algorithm confusion attacks

A well-known class of attack tries to trick a verifier into checking a token’s signature using the wrong algorithm than the one Keycloak actually signed it with — for instance, treating an asymmetric RS256 signature as if it were a symmetric HS256 one, using the public key as if it were a shared secret. This isn’t a flaw in rotation itself, but rotation forces every client integration to be reviewed periodically, which is a good moment to confirm client libraries pin the expected algorithm rather than trusting whatever the token claims.

!
Common Mistake

Never let a verifying application decide which algorithm to use based purely on the token’s own header. The expected algorithm and expected key set should be configured on the verifier’s side, independent of what the incoming token claims.

Protecting the private key material itself

Rotation reduces the impact of a leaked key, but it is not a substitute for protecting the key in the first place. Production deployments are strongly encouraged to store private key material in a hardware security module (HSM) or a dedicated secrets manager rather than in Keycloak’s database in plain configuration, and to restrict who can read or export key material through the admin console.

Encryption keys vs. signing keys

Keycloak also supports a separate rsa-enc provider type used for encrypting content (such as encrypted ID tokens or SAML assertions) rather than signing it. These follow the same priority-and-active mechanics as signing keys, but rotating an encryption key requires extra care: anything that was encrypted under the old key must still be decryptable, which usually means keeping the old encryption key enabled for even longer than a typical signing key’s grace period.

7Monitoring, Logging & Metrics

A rotation you can’t observe is a rotation you’re performing on faith. Here’s what’s worth watching.

kid
field to log on every verification failure
/certs
endpoint to watch for unexpected shape changes
TTL
of client-side JWKS cache to audit

What to log

Whenever a token fails signature verification on the application side, the log entry should capture the token’s kid value. Over time, a spike in failures referencing a particular kid is a strong signal that a key was retired too early, or that a client is caching a stale public key set.

What to monitor operationally

Administrators rotating keys should track: how many keys are currently enabled per realm, which one is presently active, how long each passive key has existed since it stopped signing, and whether any custom key’s underlying certificate is approaching its own expiry date (which is a separate clock from Keycloak’s own priority settings).

Simple Analogy

Monitoring key rotation is like tracking expiry dates in a pharmacy. You don’t just care whether today’s stock is fresh — you care whether any older stock still on the shelf is quietly approaching its cutoff date, so nobody reaches for it after it should have been pulled.

Metrics worth alerting on

A sudden increase in authentication or token-verification error rates immediately following a known rotation event is the clearest early-warning signal available. Equally, an old key that has remained enabled far past its intended grace period is worth alerting on too — it represents unnecessary exposure that nobody has cleaned up.

8Design Patterns & Anti-Patterns

Some ways of rotating keys are well-trodden and safe. Others look reasonable but cause outages.

The overlapping-keys pattern

The recommended pattern — and the one Keycloak’s priority system is built around — is to always have at least two enabled keys during a transition: the new key signing everything going forward, and the old key still available purely to verify what it already signed. This overlap is what makes rotation invisible to end users.

Scheduled Rolling Rotation

A new key is introduced on a fixed calendar (for example, every 90 days), promoted to active, and the previous key is downgraded to passive on the same schedule — automated through the Admin REST API or infrastructure-as-code tooling rather than manual clicks in the console.

Emergency Rotation

Triggered by a suspected compromise. Unlike scheduled rotation, this may deliberately skip a long grace period, accepting that some active sessions will be forced to re-authenticate, because the risk of leaving the old key trusted outweighs the inconvenience.

ANTI-PATTERN-01 Avoid
Problem

Deleting the old key from the realm the same day the new key is promoted to active.

Why It’s Harmful

Any token, refresh token, or downstream artifact still referencing the old key’s kid fails verification immediately, producing a burst of user-facing login failures with no obvious cause.

Correct Approach

Keep the old key enabled and passive for at least as long as the longest-lived token type or session it could be validating, then remove it.

ANTI-PATTERN-02 Avoid
Problem

Client applications hardcoding a single public key instead of dynamically resolving it from the realm’s published key set using the token’s kid.

Why It’s Harmful

The moment Keycloak rotates, the hardcoded key becomes stale and every new token fails verification on the client side, even though Keycloak itself is working correctly.

Correct Approach

Use a standard OpenID Connect client library that fetches and caches the JWKS endpoint and resolves keys by kid automatically.

9Best Practices & Common Mistakes

A short, practical checklist distilled from the mechanics covered so far.

Practice

Automate, don’t click

Use the Admin REST API or an infrastructure tool to create and promote keys on a schedule, reducing the chance of a forgotten manual step.

Practice

Size the grace period against reality

Base it on the longest-lived token or session type in your realm, not on a generic default.

Practice

Separate signing and encryption rotation

Treat rsa and rsa-enc providers as independent rotation schedules, since encrypted content may outlive typical tokens.

Practice

Audit custom key certificate expiry separately

An externally issued certificate’s own expiry date is a second clock that Keycloak’s priority settings don’t track for you.

Common mistakes to avoid

Beyond deleting keys too early, three mistakes come up repeatedly in production environments: forgetting that each realm rotates independently (so a script written for one realm silently does nothing useful in another); assuming a client library caches the JWKS endpoint forever once fetched, when most libraries actually respect a time-to-live and will eventually refresh on their own; and rotating a key without first confirming which applications actually validate tokens locally versus which ones call back to Keycloak’s introspection endpoint, since the two failure modes look different when something goes wrong.

10Real-World & Industry Examples

Key rotation isn’t a Keycloak-only idea — it’s the same pattern used across the identity industry, which is exactly why Keycloak’s design will feel familiar if you’ve used other providers.

Regulated Financial Services

Banks and payment processors deploying Keycloak as their customer identity layer often rotate signing keys on a strict quarterly cycle to satisfy auditors, with every rotation event logged and reviewed as part of a compliance trail.

SAML Federation with Partner Organizations

Organizations that federate with external partners via SAML frequently need to run two decryption keys side by side at different priorities during a transition, so that a partner who hasn’t yet updated their configuration can keep working with the old key while others move to the new one.

Multi-Tenant SaaS Platforms

Platforms that give each customer their own Keycloak realm rely on the fact that rotation is realm-scoped: one tenant’s key schedule, or even a tenant’s own emergency rotation after a security incident, has zero effect on any other tenant sharing the same Keycloak deployment.

ScenarioTypical Rotation TriggerGrace Period Emphasis
Routine compliance rotationFixed calendar scheduleLong — prioritizes zero disruption
Suspected key compromiseSecurity incidentShort or skipped — prioritizes containment
Algorithm or key-size upgradePlanned modernizationLong — allows client libraries time to adapt
Partner-facing SAML certificate renewalExternal certificate expiryCoordinated with the partner’s own update window

11Frequently Asked Questions

Q1Does rotating a key log users out immediately?

No, not under a normal scheduled rotation. Existing sessions and tokens keep working because the old key remains enabled and passive during the grace period. Users are only forced to re-authenticate if the old key is disabled or deleted before their session or token would naturally have expired.

Q2How often should keys be rotated?

There is no single universal number — it depends on your risk tolerance, compliance requirements, and token lifetimes. What matters more than the exact interval is having a repeatable, automated process and a grace period that’s genuinely long enough for your longest-lived tokens.

Q3Can I have more than two keys active at once?

You can have as many enabled keys as you like in a realm, but only one can be “active” for new signatures at any given moment based on priority. Having several passive keys around simultaneously is normal during a staged migration, such as an algorithm upgrade.

Q4Is rotating an encryption key the same as rotating a signing key?

Mechanically yes — same priority and active/enabled model — but the safe grace period is usually longer for encryption keys, since content encrypted under an old key may need to be decrypted long after it was created, unlike a token that simply expires.

Q5What happens if a client application ignores the “kid” field?

It will typically try to verify every token against whichever single key it has cached, and will start failing verification the moment Keycloak rotates. This is one of the most common causes of a “rotation broke production” incident, and the fix is always on the client side: use a library that resolves keys by kid.

12Summary and Key Takeaways

Key rotation in Keycloak is the disciplined practice of retiring signing (and encryption) keys on a schedule, without ever breaking a token that’s already been issued. It works because Keycloak treats keys as ordinary, replaceable components with priority and active/enabled flags, tags every token with a “kid” that points back to the exact key that made it, and publishes public keys through a JWKS endpoint that can list multiple keys at once. The entire safety of the process rests on one idea: never remove a key while anything still depends on it being there to verify against.

Key Takeaways

  • Rotation is routine, not reactive — it happens on a schedule, independent of whether a compromise has occurred.
  • Priority decides the active key — Keycloak always signs new tokens with the highest-priority enabled and active key in a realm.
  • The “kid” field is what makes overlap safe — every token names the exact key that signed it, so old and new keys can coexist without confusion.
  • The grace period is the real design decision — size it against your longest-lived token, session, or encrypted artifact, not a generic default.
  • Signing and encryption keys rotate separately — rsa and rsa-enc providers need their own schedules and their own grace periods.
  • Client libraries must resolve keys dynamically — hardcoding a key instead of reading the JWKS endpoint by kid is the single most common rotation-breaking mistake.
  • Rotation is realm-scoped — one realm’s key schedule, even an emergency one, has no effect on any other realm on the same Keycloak instance.