You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot 4.0.6升级后OAuth2授权服务报authenticationTime cannot be null异常

解决Spring Boot 4.0.6 + OAuth2 Authorization Server的authenticationTime cannot be null异常

问题原因

升级到Spring Boot 4.0.6后,spring-boot-starter-oauth2-authorization-server中的JwtGenerator组件对认证时间(authenticationTime)的校验逻辑变得严格,当从OAuth2Authorization对象中读取不到该字段值时,直接抛出非法参数异常。

常见触发场景:

  • 旧版本存储的授权码/授权记录未包含authenticationTime字段,升级后读取这些历史数据时触发异常
  • 自定义认证流程中,未正确设置Authentication对象的认证时间,导致生成OAuth2Authorization时缺失该字段

解决方案

1. 清理旧授权数据

如果是遗留的历史授权记录(比如Redis、数据库中的OAuth2Authorization数据)缺失authenticationTime字段,直接清理这些旧数据即可。新生成的授权记录会自动包含该字段,不会再触发异常。

2. 自定义JwtGenerator处理null值

如果无法清理旧数据,或者自定义流程中无法保证authenticationTime存在,可以重写JwtGenerator的getAuthenticationTime方法,补充默认值:

@Bean
public JwtGenerator jwtGenerator(JwtEncoder jwtEncoder) {
    return new JwtGenerator(jwtEncoder) {
        @Override
        protected Instant getAuthenticationTime(OAuth2Authorization authorization) {
            Instant authTime = super.getAuthenticationTime(authorization);
            // 当认证时间为null时,用当前时间替代
            return authTime != null ? authTime : Instant.now();
        }
    };
}

3. 在认证流程中正确设置认证时间

如果是自定义认证逻辑(比如自定义AuthenticationProvider),需要在生成Authentication对象时明确设置认证时间:

Authentication authentication = new UsernamePasswordAuthenticationToken(
        userDetails,
        null,
        userDetails.getAuthorities()
);
// 存入认证时间
authentication.setDetails(Map.of("authenticationTime", Instant.now()));

后续生成OAuth2Authorization时会自动读取该时间并存储。


内容的提问来源于stack exchange,提问作者asgarov1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 21:34:51