Access Token过期后仍可访问API问题及clockSkew配置咨询
问题解答
1. clockSkew的归属
这个clockSkew是**Spring Security(Spring Boot集成的安全组件)**默认设置的,和Keycloak无关。它的设计目的是解决分布式系统中服务器时间不一致的问题,避免因为微小的时间差导致合法Token被误判为过期,默认值为60秒,和你观测到的现象完全匹配。
2. 自定义clockSkew的方法
你无需显式引入JwtTimestampValidator,通过Spring Security的配置即可覆盖默认值,具体有两种方式:
方式一:通过配置类自定义JwtDecoder验证规则
在Spring Security配置类中,构建JwtDecoder时指定自定义的clockSkew:
import org.springframework.context.annotation.Bean; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtValidators; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import java.time.Duration; @Configuration public class SecurityConfig { @Bean public JwtDecoder jwtDecoder() { NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri("你的Keycloak JWKS地址").build(); // 示例:将clockSkew设置为10秒 decoder.setJwtValidator(JwtValidators.createDefaultWithClockSkew(Duration.ofSeconds(10))); return decoder; } }
方式二:通过配置文件直接设置
如果使用Spring Boot 2.6及以上版本,可直接在配置文件中修改:
application.yml格式
spring: security: oauth2: resourceserver: jwt: clock-skew: 10s
application.properties格式
spring.security.oauth2.resourceserver.jwt.clock-skew=10s
根据你的需求调整数值即可,比如设为0秒就能关闭时钟偏移容忍。
内容的提问来源于stack exchange,提问作者Reza Azad
相关产品推荐
相关产品推荐

