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

Spring Boot WebAPI集成Google OAuth2.0遇401 Unauthorized问题排查

问题:Spring Boot WebAPI集成Google OAuth2.0后,Bearer Token认证返回401 Unauthorized

我正尝试在Java Spring Boot WebAPI中集成Google OAuth2.0,参考Spring Security官方文档操作:

  1. 在pom.xml中添加以下依赖后,所有请求被保护:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
  1. 配置了SecurityConfiguration类:
@EnableWebSecurity
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration{

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests((authz) -> authz
        .anyRequest().authenticated()        
    )
    .httpBasic(withDefaults());
    return http.build();            
    }
}
  1. API接口代码:
@RequestMapping(value = "testauth", method = RequestMethod.GET)
public ResponseEntity<Object> createTask() {
  
    String result = "Hellow World"; 
    return new ResponseEntity<>(result, HttpStatus.OK);
}

完成配置后,即使使用从Google OAuth获取的正确Bearer Token作为请求头认证,所有API请求仍返回401 Unauthorized,想了解缺失哪些配置导致请求被拒绝?


解决方案:缺失的关键配置

你的问题核心是未配置OAuth2资源服务器来解析和验证Google签发的Bearer Token,具体缺失以下配置:

1. 缺少OAuth2资源服务器依赖

当前仅引入的spring-boot-starter-oauth2-client是用于实现OAuth2客户端跳转授权登录的依赖,而验证Bearer Token需要添加资源服务器依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

2. SecurityFilterChain配置错误

当前配置的httpBasic(withDefaults())是基于用户名密码的HTTP基础认证逻辑,完全不处理OAuth2的Bearer Token。需要替换为OAuth2资源服务器配置,让Spring Security能解析JWT格式的Token:

修改后的SecurityConfiguration:

import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authz -> authz
                .anyRequest().authenticated()
            )
            // 替换httpBasic为OAuth2资源服务器配置,专门处理Bearer Token验证
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }
}

3. 缺少Google OAuth2的JWT验证配置

需要在配置文件中指定Google的JWT签发者URI,Spring Security会自动从该地址获取JWKS公钥,用于验证Token的签名、有效期、签发者等合法性信息:

application.yml示例:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://accounts.google.com

application.properties示例:

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://accounts.google.com

验证逻辑说明

添加以上配置后,Spring Security会自动执行以下操作:

  • 从请求头的Authorization: Bearer <token>中提取Token
  • 通过配置的issuer-uri获取Google的JWKS公钥,验证Token的签名有效性
  • 检查Token的有效期、签发者等字段是否合法
  • 验证通过后,允许请求访问受保护的接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:06:27