Sub topic 15
Key rotation and JWK set caching
This chapter assumes you have a working JWT resource server, as built in the earlier chapters. You should know what kid and jwk-set-uri mean, and how NimbusJwtDecoder verifies a signature. Here you will see what happens to those pieces when the authorization server replaces its signing key.
Why keys rotate
An authorization server signs every JWT with a private key. Your API verifies the signature with the matching public key, which it downloads from a JWK set endpoint (JWKS). Rotation means replacing the signing key with a new one on a schedule, or immediately after a suspected leak.
Rotation limits the damage of a leaked key. It also lets you change algorithms, for example from RS256 to ES256. The difficulty is that the server and many resource servers all have to agree on which keys are valid at any moment, and they do not update at the same time.
The rotation sequence
A well-run provider rotates in four phases, so tokens signed with the old key stay verifiable until they expire.
| Phase | JWKS contains | Signing key | Effect on your API |
|---|---|---|---|
| 1. Steady state | key A | A | Tokens carry `kid` A. |
| 2. Publish | keys A and B | A | Your API can cache B before any token uses it. |
| 3. Switch | keys A and B | B | New tokens carry `kid` B. Old tokens still verify with A. |
| 4. Retire | key B | B | Tokens signed with A are rejected. |
Phase 4 must wait at least as long as the longest token lifetime. If the provider removes A while 15-minute tokens signed with A are still in circulation, those tokens start failing before they expire.
How Spring Security finds and caches keys
When you set jwk-set-uri or issuer-uri, Spring Boot builds a NimbusJwtDecoder that uses the Nimbus library to fetch the JWK set over HTTP. For each incoming token the decoder reads the kid header, selects the matching key, and verifies the signature.
Two behaviors matter for rotation:
- The decoder caches the fetched JWK set rather than downloading it for every request. The Spring Security reference documents a default cache lifetime of about five minutes. Check the documentation for your version, because defaults have changed between releases.
- When a token names a
kidthat is not in the cached set, the decoder fetches the set again and retries the lookup. This is what makes phase 3 work without a restart.
With issuer-uri, Spring Boot first reads the provider's discovery document to find the jwks_uri. This happens lazily on the first request in recent Boot versions, so a provider outage at startup does not stop your application from booting. With jwk-set-uri the discovery step is skipped, and the decoder does not check the iss claim unless you add that validator yourself.
spring:
security:
oauth2:
resourceserver:
jwt:
jwk-set-uri: https://issuer.example.com/realms/demo/protocol/openid-connect/certs
jws-algorithms: RS256Pinning jws-algorithms means a token signed with an unexpected algorithm is rejected even if the provider publishes a key for it.
Controlling the cache
The default cache behavior is often fine. Change it when you need a shorter delay before a retired key stops working, or fewer requests to the provider.
The builder accepts any Spring Cache. This example uses Caffeine with a fixed expiry. It needs spring-context-support and com.github.ben-manes.caffeine:caffeine on the classpath.
import java.time.Duration;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
@Configuration
public class JwkCacheConfig {
@Bean
JwtDecoder jwtDecoder() {
CaffeineCache cache = new CaffeineCache("jwks",
Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(2))
.build());
return NimbusJwtDecoder
.withJwkSetUri("https://issuer.example.com/realms/demo/protocol/openid-connect/certs")
.jwsAlgorithm(SignatureAlgorithm.RS256)
.cache(cache)
.build();
}
}This bean replaces the one Boot would auto-configure from properties. If you still need issuer and audience checks, call decoder.setJwtValidator(...) as shown in the validation chapter. Otherwise you lose them.
Failure modes
A key is retired but still accepted. If the provider removes key A, your API keeps accepting tokens signed with A until its cached set expires. For routine rotation this is harmless. After a key compromise it is a real window of exposure. In that case the provider should rotate immediately, and you should be ready to restart the API or shorten the cache lifetime.
The new key arrives before the cache refreshes. This is the case the unknown-kid refresh handles. Problems appear when the token has no kid header. The decoder then has to try every key in the set, and if the cached set is stale, it cannot recover through a targeted refresh. Prefer providers that always set kid.
The JWKS endpoint is down. A cached set keeps working until it expires. After that, requests that need verification fail, and Spring returns 401 because the token cannot be validated. A very short cache lifetime makes this outage worse, because the API depends on the provider for nearly every request. A lifetime of a few minutes balances freshness against availability.
Many instances refresh at once. Each application instance keeps its own cache. When a rotation happens, every instance sees the unknown kid and fetches the set at about the same moment. Most providers handle this easily. If yours rate-limits the JWKS endpoint, put a shared HTTP cache or gateway in front of it.
Unknown kid values trigger fetches. A client can send tokens with random kid values, and each one can cause a refresh of the JWK set. Nimbus limits refresh frequency in recent versions, but do not rely on that alone. Apply rate limiting at your gateway or load balancer, and reject requests with no Authorization header before they reach the decoder.
Signing algorithm changes. If the provider moves from RS256 to ES256 and you pinned jws-algorithms: RS256, valid tokens fail with 401 after the switch. List both algorithms during the transition, then remove the old one.
Checking rotation in practice
You can confirm rotation behavior without waiting for the provider's schedule.
- Fetch the JWKS endpoint with
curland note thekidvalues. - Decode the header of a real token (the first segment, Base64URL-encoded) and confirm its
kidappears in the set. - In a test environment, rotate the key on the provider and request a new token.
- Call your API with the new token. A 200 response means the unknown-
kidrefresh worked. - Call it with a token issued before rotation. It should still succeed until that token expires or the old key is retired.
Summary of decisions
| Question | Guidance |
|---|---|
| How long should the cache live? | A few minutes. Shorten it only if you need fast retirement of keys. |
| Should I pin algorithms? | Yes. List every algorithm the provider uses during a transition. |
| Who controls overlap between old and new keys? | The provider. It should keep old keys published for at least the longest token lifetime. |
| What if a key leaks? | Rotate at the provider, remove the old key, and restart or flush the cache on your API. |
Exercise
Your provider rotates its signing key and removes the old key from the JWKS endpoint right away. Your API caches the JWK set for 5 minutes, and access tokens last 15 minutes. Describe what clients holding tokens signed with the old key experience, and what the provider should have done instead.
Show answer
Within the cache window, tokens signed with the old key may still verify, because the old key is still cached. Once the cache expires and the set is fetched again, the old key is gone, so every token signed with it fails signature verification and the API returns 401. This can happen up to 15 minutes before those tokens expire. The provider should have published the new key alongside the old one, switched signing to the new key, and kept the old key published for at least the 15-minute token lifetime (plus the cache lifetime) before removing it.
Exercise
A token arrives with a kid that is not in your cached JWK set. What does the decoder do, and why does that make phase 2 of the rotation sequence (publishing the new key early) less critical but still useful?
Show answer
The decoder fetches the JWK set again and looks up the kid in the fresh set, so a new key can be picked up without a restart. Publishing the key early is still useful because the key is then already cached when the first token signed with it arrives. That avoids an extra network call on the request path and avoids failures if the JWKS endpoint is briefly unavailable at the moment of the switch.