如何用Postman/Bruno测试OAuth2认证的Spring Boot API?
解决Spring Boot Google OAuth2 API测试的Bearer Token 401问题
你遇到的核心问题是:按官方指南配置的Spring Boot是OAuth2客户端(会话式认证),只认自己生成的JSESSIONID cookie,不会处理Google的Bearer Token。要让API同时支持前端会话登录和Postman/Bruno的Bearer Token测试,得把Spring Boot同时配置成OAuth2客户端和资源服务器。
步骤1:添加资源服务器依赖
在pom.xml(Maven)或build.gradle(Gradle)里加入资源服务器依赖:
Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
Gradle
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
步骤2:配置资源服务器的JWT验证
在application.yml或application.properties里添加Google JWT的验证配置:
application.yml
spring: security: oauth2: client: registration: google: client-id: 你的Google客户端ID client-secret: 你的Google客户端密钥 scope: openid, email, profile resourceserver: jwt: issuer-uri: https://accounts.google.com
这个配置让Spring自动从Google获取公钥,验证access token的签名和合法性。
步骤3:调整安全配置类,支持两种认证方式
修改你的SecurityConfig,让前端页面走会话式登录,API路径走Bearer Token验证:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 对API路径启用Bearer Token验证 .authorizeHttpRequests(auth -> auth .requestMatchers("/api/**").authenticated() .anyRequest().permitAll() ) // 前端页面用OAuth2登录(会话式) .oauth2Login(oauth2 -> oauth2 .loginPage("/login") // 可自定义登录页或用默认 ) // API用资源服务器的JWT验证 .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt // 可自定义JWT解析逻辑,比如提取用户信息 ) ) // 会话配置,前端用cookie保持登录 .sessionManagement(session -> session .sessionFixation().migrateSession() ); return http.build(); } }
步骤4:用Postman正确获取并使用Token
- 在Postman里新建请求,选择Authorization标签
- 类型选OAuth 2.0,点击Get New Access Token
- 配置参数:
- Token Name: Google Token
- Grant Type: Authorization Code
- Callback URL: 和Google控制台配置一致的回调地址(比如
http://localhost:8080/login/oauth2/code/google) - Auth URL:
https://accounts.google.com/o/oauth2/v2/auth - Access Token URL:
https://oauth2.googleapis.com/token - Client ID: 你的Google客户端ID
- Client Secret: 你的Google客户端密钥
- Scope:
openid email profile
- 点击Request Token,登录Google账号授权后,Postman会自动把Bearer Token加到请求头里
- 发送API请求,就能正常通过认证了
为什么原来的Bearer Token会返回401?
之前的配置只启用了OAuth2客户端模式,Spring Boot会在用户登录后创建自己的会话,用JSESSIONID cookie跟踪身份,根本不会解析请求头里的Bearer Token。只有配置了资源服务器,Spring才会处理Bearer Token并验证其合法性。
内容的提问来源于stack exchange,提问作者user178456
相关产品推荐
相关产品推荐

