How to Handle JWT Key Rotation with JWKS
Rotate JWT signing keys without invalidation: publish a JWKS with a kid, keep old keys to verify, and let verifiers select the key by kid.
On this page
Introduction
A JWT is signed with a private key, and verifiers check the signature with the corresponding public key. If you ever need to change the signing key, and you will, every verifier that only knows the old key will reject new tokens, and everything that knows only the new key will reject old ones. The way to rotate without an outage is a key set published at a stable URL, with each key identified, so a verifier can find the right one and both old and new tokens verify during the transition.
This tutorial covers publishing a JWKS, using a key id to select the key, retaining old keys long enough for outstanding tokens to expire, and safely removing them. The examples follow the JWK, JWS, and metadata specifications so the mechanism is interoperable.
Publish a JWKS with key ids
A JSON Web Key Set is a JSON document listing public keys, each a JSON Web Key with a key id, the kid. Expose it at a stable, well-known URL, often advertised as jwks_uri in the authorization server’s metadata, so verifiers can discover it. Each key in the set is one the server may use to sign or has used recently, and the kid names it uniquely.
Use the kid everywhere a key is referenced: the JWKS lists it, and every token signed with that key carries it in the JOSE header. This turns key selection from a guess into a lookup. A verifier reads the token’s kid, finds the matching key in the set, and verifies, without trying keys it does not need and without ambiguity when several keys share an algorithm.
{
"keys": [
{ "kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256",
"kid": "2026-03", "x": "...", "y": "..." },
{ "kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256",
"kid": "2025-12", "x": "...", "y": "..." }
]
}
Sign with the current key and set the kid
At any moment, sign new tokens with the current key and include its kid in the token header. The verifier uses the kid to pick the key, so it never has to guess which key signed the token. Rotate by promoting a new key to current and demoting the old one, but do not remove the old one yet, because tokens signed with it are still in circulation.
Generate the kid deterministically or with a timestamp or a random suffix, but keep it stable for a given key and unique across keys. An ambiguous or reused kid forces the verifier to try multiple keys, which defeats the purpose and can pick the wrong key. Log the kid used to sign so you can trace which key a token came from during an incident.
import { SignJWT, importPKCS8 } from 'jose';
async function signToken(payload, privatePem, kid) {
const key = await importPKCS8(privatePem, 'ES256');
return new SignJWT(payload)
.setProtectedHeader({ alg: 'ES256', kid }) // verifier selects by kid
.setExpirationTime('5m')
.sign(key);
}
Keep old keys until their tokens expire
The core of rotation without invalidation is overlap. When you start signing with a new key, keep the old public key in the JWKS so tokens it already signed continue to verify. Keep it until every token it signed has expired, which is the maximum token lifetime plus a margin for clock skew and for tokens cached somewhere. Only then remove it from the set.
Publish the new key before you sign with it, so verifiers see it before they encounter a token that uses it. The sequence is: add the new key to the JWKS, wait for verifiers to cache it, start signing with it, keep signing with the old key valid until its tokens expire, then remove the old key. Reversing the order, signing with a key verifiers have not seen, produces a burst of verification failures.
// rotation sequence, each step separated in time
// 1. publish new key in JWKS (verifiers fetch it)
await jwks.add(newKey); // kid "2026-03"
// 2. after verifiers have cached it, start signing with it
setCurrentKey(newKey);
// 3. keep signing with the old key valid until its tokens expire
// 4. later, remove the old key from JWKS (kid "2025-12")
await jwks.remove('2025-12');
Let verifiers cache but refresh
Verifiers should cache the JWKS to avoid fetching it on every request, but must refresh it periodically so a newly published key is picked up and a removed key stops being trusted. Cache for a bounded time, such as a few minutes, and refresh when a token’s kid is not found in the cached set, which handles the case where a new key was published between refreshes. This keeps verification fast without pinning a stale key set.
Handle the unknown-kid case explicitly: on a miss, refetch the JWKS once and retry, then reject if still absent. This absorbs the normal rotation race where a token is signed with a key newer than the cached set. Do not cache indefinitely, and do not treat a miss as a permanent failure, because both turn a routine rotation into an outage.
async function verifyWithJwks(token: string, cache: { get(uri: string): Promise<unknown> }) {
const { payload, protectedHeader } = decodeProtectedHeaderSafe(token);
let set = cache.get(JWKS_URI);
if (!set.keys.some((k: { kid: string }) => k.kid === protectedHeader.kid)) {
set = await refreshJwks(); // one refetch on unknown kid
}
const key = set.keys.find((k: { kid: string }) => k.kid === protectedHeader.kid);
if (!key) throw new Error('unknown kid');
return payload;
}
Test selection and removal
Test that a token signed with the current key verifies using the kid. Test that a token signed with an old key verifies while that key is still in the JWKS, which is the overlap that makes rotation seamless. Test that after the old key is removed, a token signed with it fails, which proves the removal takes effect. Test that an unknown kid triggers one refresh and then succeeds when the key is present, and fails when it is not.
OLD=$(node scripts/issue-token.mjs key=kid-2025-12)
NEW=$(node scripts/issue-token.mjs key=kid-2026-03)
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $OLD" http://localhost:3000/me # 200 during overlap
node scripts/remove-jwks-key.mjs kid-2025-12
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $OLD" http://localhost:3000/me # 401 after removal
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $NEW" http://localhost:3000/me # 200
Common pitfalls
Signing with a key before verifiers have seen it, removing an old key before its tokens expire, omitting the kid so verifiers must try every key, caching the JWKS forever so a rotation never takes effect, and treating an unknown kid as a permanent failure instead of one refetch are the recurring mistakes. A publish-then-sign order, key retention for a full lifetime, a kid on every token, bounded caching, and a single refetch on miss address them.
Conclusion
Rotate JWT signing keys with a published JWKS and a kid. Add the new key to the set, let verifiers cache it, start signing with it, keep the old key valid until its tokens expire, then remove it. Let verifiers cache with a bounded TTL and refetch once on an unknown kid. Self-check by asserting an old-key token verifies during overlap and fails after removal. Then a key change is invisible to clients instead of an outage.
Sources: RFC 7517: JSON Web Key (JWK), RFC 7515: JSON Web Signature, RFC 8414: OAuth 2.0 Authorization Server Metadata and jwks_uri.
FAQ
- Why include a kid?
- A verifier may have several public keys during rotation. The kid in the token header tells it which one to use, so it does not have to try each. Without a kid, a verifier must attempt every key, which is slower and ambiguous when keys share an algorithm.
- How long do I keep an old key?
- Until every token it signed has expired. If access tokens live five minutes and refresh tokens are signed separately, keep the key at least that long after you stop signing with it, plus a margin for clock skew and cached tokens, then remove it.
Report a problem with this articleOpens a pre-filled issue on GitHub.