Spring Boot中JWT授权请求如何禁用过期时间校验?
当然有可行的方案!在Spring Boot中实现JWT授权时跳过exp过期时间校验,我整理了几个项目里常用的实现方式,你可以根据自己的Spring Security版本和业务场景选择:
方案1:自定义JwtDecoder(Spring Security 5.2+推荐)
这是最灵活也是最推荐的方式,通过修改JwtDecoder的校验器集合,移除默认的过期时间校验逻辑:
@Bean public JwtDecoder jwtDecoder() { // 如果你用的是JWKS密钥集,就用这个初始化方式 NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri("你的JWKS地址").build(); // 如果你用的是对称密钥,替换成下面这行: // NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec("你的对称密钥".getBytes(), "HmacSHA256")).build(); // 创建默认校验器集合,移除过期时间校验器,再添加一个空校验(不做任何检查) JwtValidator<Jwt> validator = JwtValidators.createDefault() .removeValidator(JwtValidators.createExpirationClaimValidator()) .addValidator(jwt -> Mono.empty()); decoder.setJwtValidator(validator); return decoder; }
这个方法的好处是可以精准控制哪些校验保留、哪些移除,比如你还可以保留iss(签发者)、aud(受众)等其他校验逻辑,只跳过exp。
方案2:自定义OAuth2TokenValidator
如果你的项目用的是Spring Security OAuth2的自定义认证流程,也可以写一个自定义的校验器,直接跳过exp校验:
public class SkipExpJwtValidator implements OAuth2TokenValidator<Jwt> { @Override public OAuth2TokenValidatorResult validate(Jwt token) { // 直接返回校验成功,不检查exp return OAuth2TokenValidatorResult.success(); // 如果你想保留其他校验逻辑,比如检查iss,可以这么写: // OAuth2Error error = null; // if (!"你的签发者".equals(token.getIssuer())) { // error = new OAuth2Error(OAuth2ErrorCodes.INVALID_ISSUER); // } // return error != null ? OAuth2TokenValidatorResult.failure(error) : OAuth2TokenValidatorResult.success(); } }
然后在Security配置里替换默认的校验器:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt .decoder(jwtDecoder()) .validator(new SkipExpJwtValidator()))); return http.build(); }
方案3:设置超大ClockSkew(快捷但不推荐生产用)
如果是测试环境想快速跳过校验,可以给JwtDecoder设置一个极大的时钟偏移,相当于忽略过期时间:
@Bean public JwtDecoder jwtDecoder() { NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec("你的密钥".getBytes(), "HmacSHA256")).build(); // 设置365天的时钟偏移,基本等于不校验过期 decoder.setClockSkew(Duration.ofDays(365)); return decoder; }
这个方法虽然简单,但不够严谨,生产环境不建议用,因为它不是真正移除校验,只是把过期时间的容忍度拉到极大。
重要提醒
跳过JWT的exp校验会带来安全风险,生产环境一定要谨慎使用,最好只针对特定接口(比如内部服务调用的接口、测试接口)生效。你可以结合Spring Security的请求匹配器,只对指定路径应用跳过校验的逻辑:
http.authorizeHttpRequests(auth -> auth .requestMatchers("/internal/api/**").authenticated() .anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt.decoder(customSkipExpJwtDecoder())));
内容的提问来源于stack exchange,提问作者user1968471
相关产品推荐
相关产品推荐

