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

Spring Boot集成Google OAuth2登录后,如何配置Postman调用API?

解决Postman调用Google OAuth2认证的Spring Boot API问题

你的Spring Boot应用当前配置的oauth2Login()是针对交互式浏览器登录的——浏览器会自动跳转到Google登录页完成授权并建立会话,所以能正常访问接口。但Postman作为API测试工具,需要手动获取OAuth2访问令牌并在请求中携带,具体配置步骤如下:

一、Postman中配置OAuth2令牌获取

  1. 新建GET请求,URL填写http://localhost:8081/test/
  2. 切换到Authorization标签页,授权类型选择OAuth 2.0
  3. 在「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」
  4. 点击「Get New Access Token」,在弹出浏览器中登录Google账号完成授权,Postman会自动获取访问令牌
  5. 点击「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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:20:03