PAYATHON 2026

如何用 postman/bruno 测试 OAuth2 保护的 APIs?

技术老齐

结论

当前配置使用 Spring Security 的 oauth2Login()。用户完成 Google 登录后,服务端会建立登录会话,客户端凭 JSESSIONID 访问接口。在这种模式下,Postman 或 Bruno 必须携带有效的会话 Cookie。手动复制 JSESSIONID 比较麻烦,但这种测试方法没有问题。

如果把 Google access token 直接放进 Authorization: Bearer ... 后收到 401,通常有以下原因:

  • 应用只配置了 OAuth2 Client,未配置 OAuth2 Resource Server;
  • Google access token 主要用于访问 Google API,默认并非签发给你的 API;
  • oauth2Login() 从会话中读取用户身份,不会自动解析 Bearer Token。

可以选择以下两种测试方式:

  1. 保留现有登录架构,让 Postman/Bruno 复用登录后的 JSESSIONID。
  2. 如果 API 需要支持 Bearer Token,就将其配置为 Resource Server,并使用 API 能够验证的令牌。

方式一:继续使用 JSESSIONID

Spring Boot 完成以下流程后,登录状态会保存在服务端会话中:

GET /oauth2/authorization/google
        ↓
Google 登录和授权
        ↓
GET /login/oauth2/code/google
        ↓
Spring Security 创建 Session
        ↓
Set-Cookie: JSESSIONID=...

后续请求携带 Cookie 即可:

GET /api/me HTTP/1.1
Host: localhost:8080
Cookie: JSESSIONID=0123456789ABCDEF

在 Postman 或 Bruno 中,可以将它添加到 Cookie 管理器,也可以临时添加请求头:

Cookie: JSESSIONID=0123456789ABCDEF

如果不想每次手动复制,可以这样操作:

  1. 在支持 Cookie Jar 的客户端或内置浏览器中访问:

    http://localhost:8080/oauth2/authorization/google
    
  2. 完成 Google 登录,让浏览器跳转回:

    http://localhost:8080/login/oauth2/code/google
    
  3. 检查 localhost 域下是否已经保存 JSESSIONID。

  4. 使用同一个 Cookie Jar 调用 API。

不同版本的 Postman 和 Bruno 共享系统浏览器 Cookie 的方式可能不同。如果认证是在外部浏览器中完成的,Cookie 未必会自动同步到 API 客户端。遇到这种情况,导入或复制 JSESSIONID 仍是正常的开发测试方式。

会话过期、服务重启或服务端清理会话后,这个 Cookie 会失效,需要重新登录。

为什么 Google access token 会返回 401

以下配置只启用了交互式登录:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/", "/error").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2Login(Customizer.withDefaults());

    return http.build();
}

oauth2Login() 在这里承担 OAuth2 Client 的职责:将用户重定向到 Google、处理回调并建立本地会话。配置它并不会让应用自动成为 Resource Server。

所以下面的请求不会仅凭 Bearer Token 通过认证:

Authorization: Bearer GOOGLE_ACCESS_TOKEN

Google access token 通常表示客户端访问 Google API 的权限。你的服务默认不是该令牌对应的资源服务器,不能因为令牌由 Google 返回就直接接受它。

方式二:让 API 正式支持 Bearer Token

如果前端、移动端或其他客户端需要直接调用 API,可以采用下面的架构:

客户端 -> Authorization Server -> 获取 access token
客户端 -> Spring Boot API,携带 Bearer Token
Spring Boot API -> 验证签名、issuer、audience、过期时间和权限

Spring Boot API 需要加入 Resource Server 依赖。Maven 示例:

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

然后启用 JWT 验证:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/", "/error").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2Login(Customizer.withDefaults())
        .oauth2ResourceServer(resourceServer ->
            resourceServer.jwt(Customizer.withDefaults())
        );

    return http.build();
}

完成配置后,Spring Security 才会处理:

Authorization: Bearer <token>

启用 Resource Server 只是基础配置。服务器还需要知道令牌由谁签发、如何验签,以及令牌的 aud 是否包含当前 API。

能否把 Google ID token 当作 Bearer Token

在受控开发环境中,可以明确配置 API 来验证 Google ID token。此处需要使用 ID token,不能把 Google access token 当成同一种令牌。

两者用途不同:

  • access token:用于访问授权服务器保护的资源;
  • ID token:用于向客户端证明用户身份,通常是 JWT。

如果 API 决定接受 Google ID token,至少需要验证:

  • JWT 签名;
  • iss;
  • exp;
  • aud,其值必须是自己的 Google OAuth Client ID。

以下示例使用 Spring Boot 3 和 Spring Security 6 的配置风格:

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

app:
  google:
    client-id: ${GOOGLE_CLIENT_ID}

增加 audience 校验:

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtDecoders;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

@Bean
JwtDecoder jwtDecoder(
        @Value("${app.google.client-id}") String clientId) {

    String issuer = "https://accounts.google.com";

    NimbusJwtDecoder decoder =
        (NimbusJwtDecoder) JwtDecoders.fromIssuerLocation(issuer);

    OAuth2TokenValidator<Jwt> audienceValidator = jwt -> {
        List<String> audience = jwt.getAudience();

        if (audience != null && audience.contains(clientId)) {
            return OAuth2TokenValidatorResult.success();
        }

        OAuth2Error error = new OAuth2Error(
            "invalid_token",
            "The required audience is missing",
            null
        );

        return OAuth2TokenValidatorResult.failure(error);
    };

    decoder.setJwtValidator(
        new DelegatingOAuth2TokenValidator<>(
            JwtValidators.createDefaultWithIssuer(issuer),
            audienceValidator
        )
    );

    return decoder;
}

Postman 或 Bruno 需要通过 OAuth 2.0 Authorization Code 流程取得包含 openid scope 的令牌,并将工具提供的回调地址准确登记到 Google OAuth Client 的 redirect URI 列表中。取得 ID token 后,可以这样测试:

GET /api/me HTTP/1.1
Host: localhost:8080
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...

控制器读取的 principal 也会从 OAuth2User 变为 Jwt:

import java.util.Map;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
class UserController {

    @GetMapping("/api/me")
    Map<String, Object> me(@AuthenticationPrincipal Jwt jwt) {
        return Map.of(
            "subject", jwt.getSubject(),
            "email", jwt.getClaimAsString("email"),
            "name", jwt.getClaimAsString("name")
        );
    }
}

是否将 ID token 用作 API 凭证,需要在架构层面决定。不要为了消除 401 而临时接受任意 JWT。生产环境更常见的方案是使用专门的 Authorization Server 联合 Google 登录,再签发 audience 指向本 API 的 access token。

Postman/Bruno 中的 OAuth2 配置边界

现有的 Spring Boot 应用本身是一个 OAuth2 Client。如果 Postman 或 Bruno 也要独立执行 Authorization Code 流程,它就是另一个 OAuth2 Client,需要单独配置:

  • Client ID;
  • Client Secret,是否需要取决于客户端类型和流程;
  • redirect URI;
  • scope;
  • Authorization URL;
  • Token URL。

工具不能直接接管 Spring Boot 的 /login/oauth2/code/google 回调。这个回调属于 Spring Security,授权码会由 Spring Boot 使用,最终转成 JSESSIONID,不会交给 Postman 或 Bruno。

测试当前的 Web 登录应用时,复用 Session 最省事。测试 Bearer Token API 时,则需要把工具注册为合适的 OAuth2 Client,同时将 API 配置成 Resource Server。

CSRF 也可能影响测试

使用 Session Cookie 调用 POST、PUT、PATCH 或 DELETE 时,即使认证成功,也可能因缺少 CSRF Token 返回 403。这和认证失败导致的 401 是两个问题。

如果 API 使用 Bearer Token,通常会对相应的 API 路径采用无状态安全配置,并根据实际架构处理 CSRF。例如,只忽略明确的 API 路径:

http.csrf(csrf -> csrf
    .ignoringRequestMatchers("/api/**")
);

仍依赖浏览器 Cookie 的页面接口不应随意关闭 CSRF,否则会削弱浏览器会话的请求保护。

如何选择

如果当前应用仍采用传统的 Spring Security 登录和 Session:

  • 保留 oauth2Login();
  • 在 Postman/Bruno 中复用 JSESSIONID;
  • 处理会话过期和 CSRF Token。

如果 API 要作为独立服务供多个客户端调用:

  • 配置 oauth2ResourceServer();
  • 使用为该 API 签发的 access token;
  • 验证签名、iss、aud、exp 和权限;
  • 不要默认接受任意 Google access token。

当前手动复制 JSESSIONID 的方法是可行的,只是自动化程度较低。Bearer Token 返回 401,是因为服务器采用 Session 登录模型,却没有配置为接受该令牌。

备注:内容仅供参考。