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

Spring Boot集成Google OAuth2.0登录遇invalid_id_token错误求助

解决Spring Boot集成Google OAuth2登录时的invalid_id_token错误

错误原因分析

invalid_id_token 错误提示ID Token包含无效的iat(签发时间)声明,最常见的原因是本地服务器系统时间与Google服务器时间偏差过大(超过JWT默认的5分钟时间容错窗口),导致Spring Security验证签发时间时判定为无效。此外,也可能是JWT验证规则配置缺失或OAuth2客户端参数不完整。

解决方案

1. 同步服务器系统时间

先检查服务器系统时间,确保和标准时间一致:

  • Linux系统:执行命令 sudo ntpdate ntp.ubuntu.com(或其他可信NTP服务器)同步时间
  • Windows系统:在日期和时间设置中开启“自动设置时间”

同步后重新测试登录,多数情况下可解决该问题。

2. 自定义JWT验证规则(可选)

若无法调整服务器时间,可通过自定义JwtDecoder放宽时间验证的容错范围:

修改Security配置类,添加自定义JwtDecoder Bean:

package com.silva.oauth2.social.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

import java.time.Duration;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(request -> request.anyRequest().authenticated())
                .oauth2Login(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    JwtDecoder googleJwtDecoder(ClientRegistrationRepository clientRegistrationRepository) {
        var clientRegistration = clientRegistrationRepository.findByRegistrationId("google");
        NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(clientRegistration.getProviderDetails().getJwkSetUri()).build();
        // 设置10分钟的时间容错窗口,可按需调整
        jwtDecoder.setJwtValidator(jwtDecoder.getJwtValidator().withClockSkew(Duration.ofMinutes(10)));
        return jwtDecoder;
    }
}

3. 完善application配置(补充必要参数)

确保配置中包含Google OAuth2的核心参数,尤其是必须的scope和issuer信息:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            clientId: <client-id>
            clientSecret: <client-secret>
            scope: openid, email, profile  # 必须包含openid,否则Google不会返回ID Token
        provider:
          google:
            issuer-uri: https://accounts.google.com  # 指定Google的issuer,辅助JWT验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:22:46