一、问题描述
在集成 Spring Security OAuth2 的 Resource Server 并采用 JWT 模式后,实际使用过程中发现 JWT 的失效时间(exp)并不是严格按照令牌中的 exp 属性来判定。多次测试后发现,JWT 实际失效时间比 exp 属性晚了约1分钟。这意味着,令牌过期后,服务端仍会有一分钟的“宽限期”允许访问。这种行为可能导致安全隐患,尤其是在对令牌有效期要求严格的场景下。
二、如何修改JwtDecoder的时间偏移量
通过分析 Spring Security OAuth2 的源码,包括 OAuth2ResourceServerConfigurer、JwtConfigurer、JwtDecoder 以及 NimbusJwtDecoder,发现 JWT 的时间校验逻辑由 JwtTimestampValidator 控制。默认情况下,JwtTimestampValidator 会有60秒的时钟偏移量(Clock Skew),用于容忍服务器之间的时间不同步。

NimbusJwtDecoder 支持自定义 JwtValidator,而 JwtTimestampValidator 的构造方法可以传入 Duration 类型的偏移量。

要严格按照 JWT 的 exp 属性判定令牌有效期,可以将时钟偏移量设置为0,只需将其设置为 Duration.ZERO 即可,具体做法如下:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import java.time.Duration;
@Configuration
public class MyJwtDecoderConfig implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof NimbusJwtDecoder nimbusJwtDecoder) {
// 设置JwtValidator的时间偏移量为0,令JWT严格按照exp属性判定有效期
nimbusJwtDecoder.setJwtValidator(JwtValidators.createDefaultWithValidators(new JwtTimestampValidator(Duration.ZERO)));
return nimbusJwtDecoder;
}
return bean;
}
}
4238

被折叠的 条评论
为什么被折叠?



