如何修改Spring Boot Authorization Server资源端Nimbus缓存过期时间?
解决方案
修改Nimbus JWT解码缓存过期时间
在资源服务器中,你可以通过自定义JwtDecoder Bean,配置缓存的过期时间,具体实现如下:
- 构建
NimbusJwtDecoder实例后,通过setCache()方法指定自定义缓存策略,设置所需的过期时长。 - 可直接基于Caffeine缓存框架创建缓存实例,或结合Spring Cache抽象统一配置。
方式1:直接创建Caffeine缓存
import org.springframework.cache.caffeine.CaffeineCache; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import com.github.benmanes.caffeine.cache.Caffeine; import java.util.concurrent.TimeUnit; @Configuration public class ResourceServerConfig { @Bean public JwtDecoder jwtDecoder() { // 替换为你的授权服务器JWKS地址 NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri("http://your-auth-server/oauth2/jwks").build(); // 设置缓存过期时间为30分钟(可根据需求调整) CaffeineCache jwtCache = new CaffeineCache("jwt-cache", Caffeine.newBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .build()); decoder.setCache(jwtCache); return decoder; } }
方式2:结合Spring Cache统一配置
若项目已使用Spring Cache,可在配置文件中定义缓存规则,再注入使用:
application.yml配置:
spring: cache: cache-names: jwt-cache caffeine: spec: expireAfterWrite=30m # 缓存30分钟后过期
对应Bean配置:
import org.springframework.cache.CacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; @Configuration public class ResourceServerConfig { @Bean public JwtDecoder jwtDecoder(CacheManager cacheManager) { NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri("http://your-auth-server/oauth2/jwks").build(); decoder.setCache(cacheManager.getCache("jwt-cache")); return decoder; } }
是否仅需在资源服务器端修改?
是的,仅需要在资源服务器端修改即可。
该缓存是资源服务器本地用于缓存JWT解码结果(包括Token合法性校验、Claims解析结果等)的本地缓存,与授权服务器发放的Token本身有效期、客户端会话或Cookie完全无关。既然你已确认Token、会话及Cookie均正常,修改资源服务器的本地缓存过期时间即可解决5分钟后返回401的问题。
内容的提问来源于stack exchange,提问作者totoro park
相关产品推荐
相关产品推荐

