Skip to content
Tutorials

JSON Web Key Sets (JWKS): Format, Key Rotation and Caching Without Outages

AIDToolStack EditorialNovember 7, 20269 min read
JWTJWKSOpenID ConnectAuthenticationSecurity
Share:Twitter

Your API accepts access tokens from an identity provider. It verifies them with a public key it fetched once at startup. Then the provider rotates its signing key, every new token carries a kid your process has never seen, and every request fails until someone restarts the service. That outage is entirely avoidable, and avoiding it is mostly about understanding one small JSON document: the JSON Web Key Set.

This post covers the format, how a verifier should pick a key, how to rotate keys you issue yourself, and what the big providers actually say about caching.

What a JWK Set looks like

RFC 7517 defines two things. A JWK is a JSON object representing one key. A JWK Set is an object with a required keys member holding an array of JWKs. Here's a real one, generated with jose for this post:

{
  "keys": [
    {
      "kty": "EC",
      "crv": "P-256",
      "x": "DrMeQU80ehgk-r18vksMGqqPeOUDW0a2D3cnSfbY-iw",
      "y": "I64P0XQ3noIDxBgvGasgCcOHJE6Y31h4vgXljPiwiek",
      "kid": "2Ev8Ou2jhr51p7RiqrdzAGyt96WQjX2E9R-CkuLBcvY",
      "alg": "ES256",
      "use": "sig"
    }
  ]
}

Google's set at googleapis.com/oauth2/v3/certs has the same shape, with two RSA keys that each carry kty, alg (RS256), use (sig), kid, n and e when fetched on 7 November 2026.

The members you'll meet:

MemberMeaningNotes from the specs
ktyKey type: RSA, EC, oct, OKPRequired. A set parser SHOULD skip keys with a kty it doesn't understand rather than fail.
kidKey IDFree-form string. Keys in one set should have distinct values. Matched against the token header's kid.
usesig or encOptional in RFC 7517, but OIDC requires it on every key when a set mixes signing and encryption keys.
key_ops["verify"] etc.Optional. RFC 7517 recommends not using it together with use.
algIntended algorithm, e.g. RS256Optional, but publish it. It lets verifiers reject a token whose header claims a different algorithm.
x5cCertificate chainStandard base64, not base64url. First cert must contain this key.
x5t#S256SHA-256 cert thumbprintbase64url.

The key material itself comes from RFC 7518, section 6. RSA keys carry n and e as unsigned big-endian integers in base64url with no leading zero octet (65537 encodes as AQAB). RFC 7518 explicitly calls out libraries that prepend a zero byte to n and asks implementers to omit it. EC keys carry crv, x and y, and each coordinate must be the full size for the curve, so a P-521 coordinate is always 66 octets even when it has leading zeros. RSA keys used with RS256 or PS256 must be at least 2048 bits.

Ed25519 keys use kty: "OKP" with crv: "Ed25519" and a single x, from RFC 8037. One change worth knowing: RFC 9864, published October 2025, deprecated the polymorphic JOSE algorithm name EdDSA and registered the fully specified Ed25519 and Ed448 in its place. New code should put "alg": "Ed25519" in headers and JWKs where its libraries support it.

How a verifier should find the key

For OpenID Connect providers you don't hard-code the JWKS URL. OIDC Discovery puts provider metadata at {issuer}/.well-known/openid-configuration, and its jwks_uri field is required and must be https. The same spec says the issuer in that document must be identical to the issuer URL you used to build the path and to the iss claim in tokens, compared code point by code point. The set at jwks_uri must never contain private or symmetric keys.

Flowchart: read the JWT header's alg and kid, look up kid in the key cache, verify on a hit; on an unknown kid fetch jwks_uri at most once per cooldown window, then verify if the kid appears or reject with 401 if it is still missing
Flowchart: read the JWT header's alg and kid, look up kid in the key cache, verify on a hit; on an unknown kid fetch jwks_uri at most once per cooldown window, then verify if the kid appears or reject with 401 if it is still missing

The unknown-kid branch is the part people skip. OpenID Connect Core section 10.1.1 describes rotation in exactly these terms: the signer adds new keys to the set at jwks_uri, signals the switch through kid, and the verifier knows to go back to jwks_uri when it sees an unfamiliar kid. Section 10.1 also says a kid MUST be in the JOSE header whenever the referenced set has more than one key.

The cooldown on that branch matters just as much. Anyone can send you a token with a made-up kid. If every unknown kid triggers a fetch, an attacker can turn your API into a request amplifier aimed at your identity provider, which may well rate-limit you right back.

To see what's in a token's header while debugging, paste it into our JWT decoder. It shows alg, kid and the claims, and it says plainly that it does not verify signatures, which is the right expectation for a browser tool.

Verifying against a remote JWKS with jose

jose (v6.2.15 on npm as of November 2026) handles fetching, caching and the refetch rule:

import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = "https://auth.example.com/";
// In practice, read jwks_uri from the issuer's /.well-known/openid-configuration at startup
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"), {
  cacheMaxAge: 10 * 60 * 1000, // default: 10 minutes
  cooldownDuration: 30 * 1000, // default: 30 seconds
  timeoutDuration: 5 * 1000,   // default: 5 seconds
});

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: ISSUER,
    audience: "https://api.example.com",
    algorithms: ["RS256", "ES256"], // never let the header choose freely
  });
  return payload;
}

The defaults in the comments come from the RemoteJWKSetOptions docs. Per the createRemoteJWKSet docs, it selects keys by the header's alg and kid, respects use and key_ops, and requires exactly one match. If nothing matches it refetches only once the cooldown since the last successful fetch has passed. When it still finds nothing, it throws JWKSNoMatchingKey with the stable code ERR_JWKS_NO_MATCHING_KEY, which is what you map to a 401. If a set ever has two keys that both match (no kid, same alg), jose throws JWKSMultipleMatchingKeys, and the docs show iterating over the candidates.

What the providers say about caching

Libraries pick sensible defaults, but providers publish their own guidance and it isn't identical:

SourceCache lifetimeUnknown kidOther notes
Auth05 to 10 minutes if you build your own cacheInvalidate and refetch, limited (e.g. retry once)Signs with one key at a time, but the set can hold several during rotation
Microsoft EntraCache each key by kid for 24 hours, refresh hourly in the backgroundRefresh on the hot path, but not more often than every 5 minutesNo set rollover schedule, emergency rollovers possible, always more than one valid key published
GoogleUse the HTTP cache directives on the responseNot specifiedKeys change "only infrequently"
jose defaults10 minutesRefetch after a 30 second cooldown5 second fetch timeout

Microsoft's page is the most detailed. Two points from it apply everywhere: discover and cache keys per tenant (or per issuer) even if they look shared today, and keep using the last known good keys if a refresh fails rather than dropping everything. Its pseudo code also refuses to refresh if the last successful refresh was under 5 minutes ago, which is the same idea as jose's cooldown with a longer window.

Publishing your own JWKS

If you issue tokens, you're on the other side of this. Generate a key pair, publish the public half, and sign with the private half:

import { generateKeyPair, exportJWK, calculateJwkThumbprint, SignJWT } from "jose";

const { publicKey, privateKey } = await generateKeyPair("ES256");
const jwk = await exportJWK(publicKey);
const kid = await calculateJwkThumbprint(jwk); // RFC 7638, SHA-256 by default

// Serve this at /.well-known/jwks.json
export const jwks = { keys: [{ ...jwk, kid, alg: "ES256", use: "sig" }] };

export const token = await new SignJWT({ scope: "read:orders" })
  .setProtectedHeader({ alg: "ES256", kid })
  .setIssuer("https://auth.example.com/")
  .setAudience("https://api.example.com")
  .setIssuedAt()
  .setExpirationTime("10m")
  .sign(privateKey);

Using the thumbprint as kid is suggested by RFC 7638 itself. It's computed over only the required members (crv, kty, x, y for EC; e, kty, n for RSA), so it's stable no matter what optional fields you add, and two services can derive the same kid independently. In production the private key lives in a KMS or secrets manager, not in process memory generated at boot. If you already have a PEM public key (our RSA key generator outputs SPKI PEM, for example), jose's importSPKI(pem, "RS256", { extractable: true }) followed by exportJWK turns it into a JWK.

If several internal services verify your tokens, an asymmetric key and a JWKS endpoint beat sharing an HMAC secret with all of them. Our JWT generator only signs with HS256, HS384 and HS512, so it's handy for testing HMAC flows but can't produce tokens that would verify against a JWKS.

Rotating without breaking anyone

OIDC Core says the signer SHOULD keep recently decommissioned keys in the set for a reasonable period. Combine that with the fact that verifiers cache, and you get a three-step rotation:

Timeline: Key A signs and is published; at step 1 key B is published but not used; after waiting out the longest cache TTL, step 2 switches signing to B while A stays published; after waiting out the longest token lifetime, step 3 removes A
Timeline: Key A signs and is published; at step 1 key B is published but not used; after waiting out the longest cache TTL, step 2 switches signing to B while A stays published; after waiting out the longest token lifetime, step 3 removes A
  1. Publish the new key alongside the old one. Nothing signs with it yet.
  2. Wait at least the longest cache lifetime your verifiers use, then start signing with the new key. Verifiers that refetch on unknown kid would cope anyway, but this keeps you clear of their cooldowns and of any verifier that doesn't refetch at all.
  3. Wait at least the longest token lifetime, then remove the old key. Any token signed by it has expired by then.

For an emergency (a leaked private key) you skip the waiting: remove the compromised key immediately and accept that tokens it signed will fail. That's the point. The secret scanning post covers the wider rotation drill when a key ends up in a repository.

Gotchas

  • Never fetch keys from a URL in the token. jku and x5u in a JWT header are attacker-controlled. Configure the JWKS location per issuer. The JWT security mistakes post covers this and alg confusion in detail.
  • Pin algorithms. A JWK with alg helps, but pass an explicit allow-list to the verify call too.
  • Don't assume one key. Microsoft says outright that its documents always contain more than one valid key, and that key order means nothing.
  • Mixed-up base64 flavours. x5c is plain base64 with + and /; everything else is base64url. The Base64 post explains the difference.
  • Per-tenant issuers. In multi-tenant setups, cache keys under issuer plus kid, not kid alone.
  • Serving your JWKS. RFC 7517 registers application/jwk-set+json as the media type for a set. Send cache headers that match your rotation timing. Google, for one, tells clients to cache its keys according to the response's cache directives, and some verifiers will treat yours the same way.

A quick check before shipping a verifier: does it discover jwks_uri from the issuer, cache by kid, refetch on an unknown kid with a cooldown, keep the last good set on fetch failure, pin iss, aud and algorithms, and survive the provider publishing three keys tomorrow? If yes, the next rotation will be a non-event.

AE

Written by AIDToolStack Editorial

Researched from official documentation, specifications and vendor pages, listed under Sources below. Last checked November 2026.

Sources

  1. www.rfc-editor.org/rfc/rfc7517.html
  2. www.rfc-editor.org/rfc/rfc7518.html
  3. www.rfc-editor.org/rfc/rfc8037.html
  4. www.rfc-editor.org/rfc/rfc9864.html
  5. www.rfc-editor.org/rfc/rfc7638.html
  6. openid.net/specs/openid-connect-discovery-1_0.html
  7. openid.net/specs/openid-connect-core-1_0.html
  8. www.googleapis.com/oauth2/v3/certs
  9. developers.google.com/identity/openid-connect/openid-connect
  10. auth0.com/docs/secure/tokens/json-web-tokens/json-web-key-sets
  11. learn.microsoft.com/en-us/entra/identity-platform/signing-key-rollover
  12. github.com/panva/jose
  13. github.com/panva/jose/blob/main/docs/jwks/remote/functions/createRemoteJWKSet.md
  14. github.com/panva/jose/blob/main/docs/jwks/remote/interfaces/RemoteJWKSetOptions.md
  15. github.com/panva/jose/blob/main/docs/key/generate_key_pair/functions/generateKeyPair.md
  16. github.com/panva/jose/blob/main/docs/jwt/sign/classes/SignJWT.md
  17. github.com/panva/jose/blob/main/docs/util/errors/classes/JWKSNoMatchingKey.md
  18. www.npmjs.com/package/jose

Related Posts

Explore on AIDToolStack

Discover tools and servers featured in our directory.

MCP Servers

Trigger.dev Jobs MCP ServerManage Trigger.dev background jobs from your AI coding assistant. Monitor job runs, trigger tasks manually, inspect execution logs, manage schedules, and debug failed runs. The server provides operational visibility into your background job infrastructure — see which tasks are running, queued, or failed, and take action. Your AI can help diagnose job failures from execution logs, retry failed tasks, and optimize concurrency configurations for better throughput.Tailscale Network MCP ServerManage your Tailscale mesh VPN network from your AI coding assistant. View connected devices, manage ACLs, configure exit nodes, check device status, and manage DNS settings. The server provides visibility into your Tailscale network — see which machines are online, troubleshoot connectivity issues, manage network access policies, and configure routes. Useful for developers managing distributed infrastructure where Tailscale provides secure networking between services.Portainer Docker MCP ServerManage Docker environments through Portainer's API from your AI coding assistant. Control containers, images, networks, and volumes across multiple Docker hosts and Kubernetes clusters. The server provides tools for container lifecycle management, image pulling and building, stack deployment, and resource monitoring. Portainer's multi-environment management makes this server particularly valuable for teams managing containers across development, staging, and production environments.

Reviews

Sign in to leave a review.

No reviews yet. Be the first!

Comments

Sign in to leave a comment.

No comments yet. Be the first!

Sponsor Our Newsletter

Reach thousands of developers who are actively evaluating AI tools, MCP servers, and dev infrastructure. Our weekly newsletter goes to engaged technical decision-makers.

Growing subscriber baseHigh open rates

All sponsored content is clearly labeled per our editorial policy.