← Blog
November 26, 202610 min readSecurity EngineeringAppSecAuthentication

JWKS key rotation for JWT verifiers: caching, cooldowns and issuer binding

Identity providers rotate signing keys on their own schedule, sometimes with no warning. The few lines that point your API at a JWKS URL decide whether logins survive it, whether junk kid values can turn your service into a request amplifier, and how long a revoked key keeps working. What jose and PyJWT do by default, why cache lifetime is revocation delay, one key set per issuer, and a rotation rehearsal you can run in staging.

By The Xalgorix Team

Microsoft's documentation for Entra ID puts the contract plainly: the platform's signing key “rolls on a periodic basis and, in the case of an emergency, could be rolled over immediately. There's no set or guaranteed time between these key rolls.” Every service that verifies JWTs from an identity provider lives with some version of that sentence. The keys that sign your users' tokens will change on a schedule you do not control, and occasionally with no warning at all.

The code that copes with this is usually a few lines: point a library at a JWKS URL and let it cache. Those few lines make three security-relevant decisions that rarely get reviewed. They decide whether logins survive a rotation, whether a stream of junk tokens can turn your API into a request amplifier aimed at your identity provider, and how long a signing key your provider has revoked keeps working in your service. This guide walks through each one, shows what two widely used libraries (jose for JavaScript and PyJWT for Python) actually do by default, and ends with a short set of tests you can run before your provider rotates for real.

How providers rotate, and what that asks of you

A JSON Web Key Set is a JSON document listing public keys. Each key usually carries a kid, and a signed token names the key that signed it in its own kid header. RFC 7517 §4.5 describes exactly this use: kid exists “to match a specific key”, for example to choose among the keys in a set during key rollover.

OpenID Connect leaves the timing of a rotation to the signer. OpenID Connect Core 1.0 says “the signer can begin using a new key at its discretion and signals the change to the verifier using the kid value”; a verifier that sees an unfamiliar kid is expected to go back to the provider's jwks_uri. Nothing in that text obliges the provider to publish a key some minimum time before signing with it. Well-run providers do stage keys anyway. Auth0's rotation documentation says its key set “will always include both the current key and the next key”, plus the previous key until you revoke it, and Microsoft says there is “always more than one valid key” in its metadata. But a verifier has to handle the unstaged case too, because the emergency roll is exactly when it happens.

Before
Sign with APublish A + B (next)
Switch
Sign with BPublish A (previous) + BOld A tokens still valid
Retire
Remove A from the setOnly B verifies
Emergency
Remove compromised key nowSign with a key nobody has cached
Each phase changes which keys a verifier must accept. Emergency rotations skip the overlap and go straight to the last row.

So a correct verifier needs four behaviours: it accepts any key currently in the set, it refetches when it meets an unknown kid, it limits how often that refetch can happen, and it drops keys that disappear from the set within a bounded time. Each common mistake breaks one of the four.

Four ways a verifier mishandles rotation

1. The key is pinned at deploy time

The public key sits in an environment variable, a mounted PEM file or a gateway setting. Everything works until the provider signs with a different key, and then every login fails until someone redeploys. Auth0's rotation page calls out exactly this for gateways that need a manually configured certificate file: the change has to be coordinated by hand. It is an availability bug, but it tends to produce a security one. Teams under pressure during the outage loosen verification “temporarily”, and some never tighten it again.

2. The cache expires, but an unknown kid never forces a refetch

A cache with a time-to-live and no other refresh trigger rejects tokens signed with a new key until the TTL runs out. With a one-hour TTL and an emergency rotation, that is up to an hour of failed logins. The fix is the behaviour OpenID Connect describes: on an unknown kid, fetch the set again before rejecting the token.

3. Every unknown kid triggers a fetch

The kid header arrives with the token, and anyone can write a token. If each unknown value causes an outbound request, an attacker who sends a few thousand requests with random kid values makes your service send a few thousand requests to your identity provider. At best that is wasted latency on every request. At worst the provider rate-limits your egress IPs and legitimate refreshes start failing, which turns a junk-token flood into a login outage. Signature checks cannot help here, because the fetch happens before there is a key to check the signature with.

The defence is a cooldown: after a successful fetch, an unknown kid may not trigger another one until a minimum interval has passed. Concurrent misses should also share one in-flight request rather than each starting their own. Microsoft's rollover guidance describes the same idea: a synchronous fetch for an unknown key, “but no more frequently than 5 mins”.

4. A failed fetch empties the cache

If the provider's JWKS endpoint returns an error for a minute and your code responds by clearing its cached keys, a short outage upstream becomes a full outage in your service. PyJWT's client is written to avoid it; a comment in the 2.15.1 source explains that writing the cache in a finally block on error “clears any previously-cached JWKS, turning a transient outage into a cache wipe that breaks legitimate auth.” Microsoft recommends the opposite of a wipe: if fetching fails, keep operating with the last known good configuration.

Token header names a kid the cache does not hold
No refetch
Rejected until the TTL expires. Rotations cause outages.
Refetch every time
Attacker-chosen kids drive outbound requests to the provider.
Refetch after a cooldown
One shared fetch per interval; the rest are rejected quickly.
A good verifier refetches once, rate-limited, and never discards the keys it already has because a fetch failed.

What jose and PyJWT do out of the box

Both libraries already avoid the worst of the mistakes above, which is a good reason to use them instead of hand-rolling a cache. Their defaults still deserve a look, because each number is a trade-off someone chose for you. The figures below come from reading jose 6.2.18 and PyJWT 2.15.1, the current releases on 26 November 2026.

jose's createRemoteJWKSet (options reference) caches the set for cacheMaxAge, 10 minutes by default, and allows a refetch for an unmatched key only once cooldownDuration, 30 seconds by default, has passed since the last successful fetch. Requests time out after 5 seconds, redirects are not followed, and on most runtimes concurrent reloads share one pending fetch. It does not read Cache-Control from the response, so the provider's caching hints are ignored. Once the 10 minutes are up, the next verification refetches, and if that fetch fails the verification fails: the library fails closed and does not serve the stale set.

PyJWT's PyJWKClient caches the whole set for lifespan, 300 seconds by default, with a 30-second cooldown_duration on forced refreshes for unknown key IDs and a 30-second HTTP timeout. Its docstring is candid about the cost of the cooldown: because every successful fetch starts it, “a newly rotated key may therefore wait for the cooldown period before it is fetched.” It also offers a second, optional cache. With cache_keys=True, individual keys are kept in an LRU cache that, in the library's own words, has “no time-based expiration”; a key leaves it only when newer lookups push it out or the process restarts.

The cooldown is not free. If your provider ever signs with a key it published seconds earlier, tokens can be rejected for up to one cooldown window. Thirty seconds of retries is usually an acceptable price for not being an amplifier; make it a decision rather than a surprise.

Your cache lifetime is your revocation delay

Rotation guides usually focus on accepting new keys. The other direction matters more when something has gone wrong. When a provider removes a compromised key from its JWKS, your service keeps accepting tokens signed with that key until it next refetches the set. No unknown kid will force that refetch, because the attacker's forged tokens use the old, still-cached key. Unless some other request happens to trigger a refetch, the only thing that removes it is the cache expiring.

That makes the cache lifetime a security parameter. Some concrete values:

  • jose with defaults: up to 10 minutes. Setting cacheMaxAge to Infinity, which the options reference documents as disabling expiry, means a removed key is accepted until the process restarts.
  • PyJWT with defaults: up to 5 minutes for the key set.
  • PyJWT with cache_keys=True: a removed key keeps verifying for as long as it stays in the LRU cache, with no upper bound in time.
  • Microsoft's guidance for custom implementations: a cache TTL of 24 hours with a refresh every hour. With the hourly refresh working, a removed key lingers for about an hour; if the refresh keeps failing and the last known good set is served, it lingers for up to a day.

Availability and revocation pull against each other here. Serving the last known good set during an upstream outage keeps logins working, and it also keeps a revoked key working. There is no universally right number, but there are better and worse ways to hold the tension. Keep the normal refresh interval short (minutes, not hours). If you serve a stale set when the fetch fails, cap how stale it may become and alert when you are relying on it. And give operators a way to force a refresh during an incident. jose exposes a reload() method on the resolver it returns, and PyJWT's get_jwk_set accepts refresh=True; wire one of them to an admin endpoint or a deploy hook so that “the provider revoked a key” does not have to mean “restart every pod”.

One key set per issuer, chosen from configuration

Services that accept tokens from more than one issuer, such as several tenants, a workforce and a customer identity provider, or a partner federation, add a second class of bug: a key that is valid for one issuer is accepted for another. RFC 8725 §3.8, the JWT best-current-practice document, is direct about it: when a JWT carries an iss claim, the application must check that the keys used to verify it belong to that issuer, and must reject the token if they do not.

Two patterns break that rule. The first merges every issuer's keys into one set and checks iss against an allowlist afterwards. A token signed by tenant A's key but claiming iss = tenant B then passes both checks. The second reads iss from the unverified token and builds a JWKS URL from it, which hands the attacker the same power as trusting a jku header: they choose where your keys come from.

Shared infrastructure makes the first pattern easy to miss. Microsoft notes that keys can be common across Entra tenants today and “can become distinct across tenants in the future”, and recommends discovering and caching keys separately for each tenant through the tenant-specific endpoint. When keys are shared, a valid signature tells you the token came from the platform, not which tenant issued it; only the issuer and tenant claims can tell you that, and only if you check them against the tenant you expected.

The safe shape is a fixed map from issuer to key set, built from configuration. Reading the unverified iss is fine as a lookup key into that map, provided an unknown issuer is rejected and the chosen verifier then enforces the issuer again:

import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";

// Issuer -> JWKS URL, from configuration only. Never derived from a token.
const ISSUERS = new Map([
  ["https://login.example-idp.com/tenant-a/", "https://login.example-idp.com/tenant-a/jwks"],
  ["https://auth.partner.example/", "https://auth.partner.example/.well-known/jwks.json"],
]);

// One resolver (and one cache) per issuer. cacheMaxAge doubles as the
// longest time a key removed from the set keeps verifying here.
const RESOLVERS = new Map(
  [...ISSUERS].map(([iss, url]) => [
    iss,
    createRemoteJWKSet(new URL(url), {
      cacheMaxAge: 5 * 60_000,
      cooldownDuration: 30_000,
    }),
  ]),
);

export async function verify(token: string) {
  const claimed = decodeJwt(token).iss; // unverified: used only as a map key
  const jwks = claimed ? RESOLVERS.get(claimed) : undefined;
  if (!jwks) throw new Error("unknown issuer");

  const { payload } = await jwtVerify(token, jwks, {
    issuer: claimed, // enforced again after the signature check
    audience: "https://api.example.com",
    algorithms: ["RS256", "ES256"],
  });
  return payload;
}

The PyJWT equivalent is one PyJWKClient per issuer in a dictionary, passing issuer=, audience= and an explicit algorithms= list to jwt.decode. In both cases the property that matters is that a key from one issuer's set can never be used to verify a token for another.

Rehearse a rotation before your provider runs one

All of this is testable, and most of it is cheap to test in a staging environment. Auth0's own advice is to rotate on a development tenant first. A short rehearsal covers the failure modes above:

Rotate in staging
new kid, old kept
Flood unknown kids
count JWKS fetches
Break the JWKS URL
500s and timeouts
Revoke a key
time until rejected
Swap issuers
A's key, B's iss
Run each step against a staging verifier and watch both the responses and the outbound requests to the JWKS endpoint.
  • Planned rotation. Rotate the signing key on a test tenant and confirm that tokens signed with both the new and the previous key verify, with no restart.
  • Unknown-kid flood. Send a few hundred requests with random kid values and count the outbound requests to the JWKS endpoint. Expect roughly one per cooldown interval, not one per request.
  • Upstream outage. Point the verifier at an endpoint that returns 500s or hangs. Note whether existing sessions keep working, how long for, and whether anything alerts.
  • Revocation. Remove a key from a test set and time how long tokens signed with it are still accepted. Compare the result with the number you would want during an incident, then test your forced-reload path.
  • Cross-issuer token. With two test issuers, sign a token with issuer A's key that claims issuer B. It must fail.

The last check is the one an external tester can usually run against production as well, since it needs nothing more than two accounts on two issuers the service trusts. The others depend on control of the provider or the network path, which is why they belong in your own test plan rather than in anyone's scanner, ours included.

Picking the numbers

There is no standard value for any of these settings, so here is a reasonable starting point to adjust rather than a rule. Use a library resolver rather than your own cache. Keep the key set lifetime in the 5 to 15 minute range, which is close to both libraries' defaults and bounds revocation delay to a coffee break. Keep a cooldown of tens of seconds on unknown-kid refetches. If you need to ride out provider outages, cap stale serving at an hour or so and alert when it starts. Avoid unbounded per-key caches. And keep one key set per issuer, chosen from configuration.

None of these settings shows up in a normal code review, because the code looks like a single function call. They show up the day your provider rotates in a hurry. Better to have picked them on purpose before that day.

Ready to see it prove a bug?

Start scanning on Cloud →