Spring Boot集成Google OAuth2登录后,如何配置Postman调用API?
解决Postman调用Google OAuth2认证的Spring Boot API问题
你的Spring Boot应用当前配置的oauth2Login()是针对交互式浏览器登录的——浏览器会自动跳转到Google登录页完成授权并建立会话,所以能正常访问接口。但Postman作为API测试工具,需要手动获取OAuth2访问令牌并在请求中携带,具体配置步骤如下:
一、Postman中配置OAuth2令牌获取
- 新建GET请求,URL填写
http://localhost:8081/test/ - 切换到Authorization标签页,授权类型选择OAuth 2.0
- 在「Configure New Token」区域填写以下参数:
- Token Name:自定义名称(如
Google-OAuth-Token) - Grant Type:选择「Authorization Code」
- Callback URL:必须与Google Cloud控制台中OAuth客户端配置的回调URL一致,可添加Postman默认回调
https://oauth.pstmn.io/v1/callback到Google的授权回调列表 - Auth URL:
https://accounts.google.com/o/oauth2/v2/auth - Access Token URL:
https://oauth2.googleapis.com/token - Client ID:你的
application.yml中配置的clientId值 - Client Secret:你的
application.yml中配置的clientSecret值 - Scope:添加
openid、email、profile(Google OAuth授权必填的基础范围) - 勾选「Authorize using browser」
- Token Name:自定义名称(如
- 点击「Get New Access Token」,在弹出浏览器中登录Google账号完成授权,Postman会自动获取访问令牌
- 点击「Use Token」,请求会自动带上
Authorization: Bearer <token>头,发送请求即可访问接口
二、可选:让应用同时支持浏览器登录和Bearer令牌访问
如果希望应用既保留浏览器会话登录,又能接受Postman的Bearer令牌请求,可修改Security配置添加oauth2ResourceServer支持:
修改后的Security Config代码
@Configuration @EnableWebSecurity public class SecurityConfiguration { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .csrf().disable() .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .oauth2Login(Customizer.withDefaults()) // 保留浏览器登录支持 .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())); // 添加Bearer令牌支持 return httpSecurity.build(); } }
配套依赖
需在pom.xml中添加资源服务器依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
三、关键配置检查
- 确认Google Cloud控制台的OAuth客户端设置中,已将Postman回调URL(如
https://oauth.pstmn.io/v1/callback)和Spring Boot默认回调URL(http://localhost:8081/login/oauth2/code/google)添加到「已授权的重定向URI」列表 - 确保Google账号有权限访问该OAuth客户端(Google Cloud中需配置测试用户或设置为公开访问)
内容的提问来源于stack exchange,提问作者Sahil Sahu
相关产品推荐
相关产品推荐

