跳到主要内容
版本:7.0.2

测试 OAuth 2.0

DeepSeek V3 中英对照 Mocking OAuth2 Testing OAuth 2.0

在 OAuth 2.0 的场景下,之前讨论的基本原则依然适用:最终取决于你的被测方法期望在 SecurityContextHolder 中获取到什么内容。

例如,对于一个如下所示的控制器:

@GetMapping("/endpoint")
public String foo(Principal user) {
return user.getName();
}

这其中并没有任何特定于 OAuth2 的内容,因此你很可能只需使用 @WithMockUser 就能顺利运行。

但是,当你的控制器与Spring Security的OAuth 2.0支持的某些方面绑定在一起时,例如:

@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OidcUser user) {
return user.getIdToken().getSubject();
}

那么 Spring Security 的测试支持就能派上用场。

测试 OIDC 登录

测试上述方法使用 Spring MVC Test 需要模拟授权服务器的某种授权流程。这无疑是一项艰巨的任务,因此 Spring Security 内置了消除这种样板代码的支持。

例如,我们可以通过 oidcLogin RequestPostProcessor 告知 Spring Security 包含一个默认的 OidcUser,如下所示:

mvc
.perform(get("/endpoint").with(oidcLogin()));

这将配置关联的 MockHttpServletRequest,使其包含一个包含简单 OidcIdTokenOidcUserInfo 以及已授权权限 CollectionOidcUser

具体来说,它将包含一个 OidcIdToken,其 sub 声明设置为 user

assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");

一个未设置任何声明的 OidcUserInfo

assertThat(user.getUserInfo().getClaims()).isEmpty();

以及一个仅包含一个权限 SCOPE_readCollection 权限集合:

assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));

Spring Security 会完成必要的工作,以确保 OidcUser 实例可用于 @AuthenticationPrincipal 注解

此外,它还将该 OidcUser 与一个简单的 OAuth2AuthorizedClient 实例关联,并将其存入模拟的 OAuth2AuthorizedClientRepository 中。如果你的测试使用了 @RegisteredOAuth2AuthorizedClient 注解,这会非常方便。

配置认证机构

在许多情况下,你的方法受到过滤器或方法安全性的保护,需要你的 Authentication 拥有特定的授予权限才能允许请求。

在这种情况下,你可以通过 authorities() 方法指定所需的授权权限:

mvc
.perform(get("/endpoint")
.with(oidcLogin()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
);

配置声明

尽管授权在所有Spring Security中相当常见,但在OAuth 2.0的情况下,我们还有声明(claims)。

例如,假设你有一个 user_id 声明,它表示用户在你系统中的 ID。在控制器中,你可以这样访问它:

@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OidcUser oidcUser) {
String userId = oidcUser.getIdToken().getClaim("user_id");
// ...
}

在这种情况下,您需要使用 idToken() 方法来指定该声明:

mvc
.perform(get("/endpoint")
.with(oidcLogin()
.idToken((token) -> token.claim("user_id", "1234"))
)
);

由于 OidcUserOidcIdToken 收集其声明。

额外配置

此外,还有更多方法可用于进一步配置身份验证;具体取决于您的控制器期望接收何种数据:

  • userInfo(OidcUserInfo.Builder) - 用于配置 OidcUserInfo 实例

  • clientRegistration(ClientRegistration) - 用于将关联的 OAuth2AuthorizedClient 与给定的 ClientRegistration 进行配置

  • oidcUser(OidcUser) - 用于配置完整的 OidcUser 实例

这在以下情况下非常方便:1. 拥有自己的 OidcUser 实现,或 2. 需要更改名称属性

例如,假设你的授权服务器在 user_name 声明中发送主体名称,而不是在 sub 声明中。在这种情况下,你可以手动配置一个 OidcUser

OidcUser oidcUser = new DefaultOidcUser(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
"user_name");

mvc
.perform(get("/endpoint")
.with(oidcLogin().oidcUser(oidcUser))
);

测试 OAuth 2.0 登录

测试 OIDC 登录类似,测试 OAuth 2.0 登录同样面临模拟授权流程的挑战。因此,Spring Security 也为非 OIDC 场景提供了测试支持。

假设我们有一个控制器,它获取已登录用户作为 OAuth2User

@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OAuth2User oauth2User) {
return oauth2User.getAttribute("sub");
}

在这种情况下,我们可以通过 oauth2Login RequestPostProcessor 来配置 Spring Security 包含一个默认的 OAuth2User,具体如下:

mvc
.perform(get("/endpoint").with(oauth2Login()));

这将配置关联的 MockHttpServletRequest,使其包含一个带有简单属性 Map 和已授权权限 CollectionOAuth2User

具体来说,它将包含一个 Map,其中包含一个键值对 sub/user

assertThat((String) user.getAttribute("sub")).isEqualTo("user");

以及一个仅包含一个权限 SCOPE_readCollection 权限集合:

assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));

Spring Security 会完成必要的工作,以确保 OAuth2User 实例可用于 @AuthenticationPrincipal 注解

此外,它还将该 OAuth2User 与一个简单的 OAuth2AuthorizedClient 实例关联起来,并将其存入模拟的 OAuth2AuthorizedClientRepository 中。如果你的测试使用了 @RegisteredOAuth2AuthorizedClient 注解,这会非常方便。

配置权限

在许多情况下,您的方法受到过滤器或方法安全的保护,需要您的 Authentication 拥有特定的授予权限才能允许请求。

在这种情况下,你可以通过 authorities() 方法指定所需的授权权限:

mvc
.perform(get("/endpoint")
.with(oauth2Login()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
);

配置声明

尽管授权在所有Spring Security中相当常见,但在OAuth 2.0的情况下,我们还有声明(claims)。

例如,假设你有一个 user_id 属性,它表示用户在系统中的 ID。在控制器中,你可能会这样访问它:

@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OAuth2User oauth2User) {
String userId = oauth2User.getAttribute("user_id");
// ...
}

在这种情况下,您需要使用 attributes() 方法来指定该属性:

mvc
.perform(get("/endpoint")
.with(oauth2Login()
.attributes((attrs) -> attrs.put("user_id", "1234"))
)
);

额外配置

此外,还有更多方法可用于进一步配置身份验证;具体取决于您的控制器期望接收何种数据:

  • clientRegistration(ClientRegistration) - 用于配置与给定 ClientRegistration 关联的 OAuth2AuthorizedClient

  • oauth2User(OAuth2User) - 用于配置完整的 OAuth2User 实例

这在以下情况下非常有用:1. 拥有自己的 OAuth2User 实现,或 2. 需要更改名称属性

例如,假设你的授权服务器在 user_name 声明中发送主体名称,而不是在 sub 声明中。在这种情况下,你可以手动配置一个 OAuth2User

OAuth2User oauth2User = new DefaultOAuth2User(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
Collections.singletonMap("user_name", "foo_user"),
"user_name");

mvc
.perform(get("/endpoint")
.with(oauth2Login().oauth2User(oauth2User))
);

测试 OAuth 2.0 客户端

无论您的用户如何进行身份验证,您可能还有其他令牌和客户端注册信息在您正在测试的请求中起作用。例如,您的控制器可能依赖于客户端凭据授权来获取一个与用户完全无关的令牌:

@GetMapping("/endpoint")
public String foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
return this.webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class)
.block();
}

模拟与授权服务器的握手过程可能相当繁琐。相反,你可以使用 oauth2Client RequestPostProcessor 将一个 OAuth2AuthorizedClient 添加到模拟的 OAuth2AuthorizedClientRepository 中:

mvc
.perform(get("/endpoint").with(oauth2Client("my-app")));

这将创建一个包含简单 ClientRegistrationOAuth2AccessToken 以及资源所有者名称的 OAuth2AuthorizedClient

具体来说,它将包含一个 ClientRegistration,其客户端 ID 为 "test-client",客户端密钥为 "test-secret":

assertThat(authorizedClient.getClientRegistration().getClientId()).isEqualTo("test-client");
assertThat(authorizedClient.getClientRegistration().getClientSecret()).isEqualTo("test-secret");

资源所有者名称为“user”:

assertThat(authorizedClient.getPrincipalName()).isEqualTo("user");

以及一个仅包含一个作用域 readOAuth2AccessToken

assertThat(authorizedClient.getAccessToken().getScopes()).hasSize(1);
assertThat(authorizedClient.getAccessToken().getScopes()).containsExactly("read");

然后,客户端可以通过在控制器方法中使用 @RegisteredOAuth2AuthorizedClient 正常获取。

配置作用域

在许多情况下,OAuth 2.0 访问令牌会附带一组权限范围。如果你的控制器需要检查这些范围,可以像这样操作:

@GetMapping("/endpoint")
public String foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
Set<String> scopes = authorizedClient.getAccessToken().getScopes();
if (scopes.contains("message:read")) {
return this.webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class)
.block();
}
// ...
}

随后,你可以使用 accessToken() 方法来配置作用域:

mvc
.perform(get("/endpoint")
.with(oauth2Client("my-app")
.accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read"))))
)
);

额外配置

此外,还有更多方法可用于进一步配置身份验证;具体取决于您的控制器期望接收何种数据:

  • principalName(String) - 用于配置资源所有者名称

  • clientRegistration(Consumer<ClientRegistration.Builder>) - 用于配置关联的 ClientRegistration

  • clientRegistration(ClientRegistration) - 用于配置完整的 ClientRegistration

如果你想使用一个真实的 ClientRegistration,最后一种方法会很方便。

例如,假设您希望使用应用程序中定义的一个 ClientRegistration,该定义已在 application.yml 中指定。

在这种情况下,你的测试可以自动装配 ClientRegistrationRepository,并查找你测试所需的那一个:

@Autowired
ClientRegistrationRepository clientRegistrationRepository;

// ...

mvc
.perform(get("/endpoint")
.with(oauth2Client()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook"))));

测试 JWT 认证

为了在资源服务器上进行授权请求,你需要一个持有者令牌。

如果你的资源服务器配置为使用JWT,那么这意味着承载令牌需要根据JWT规范进行签名和编码。所有这些都可能相当令人望而生畏,尤其是在测试的重点不在此处时。

幸运的是,有几种简单的方法可以克服这个困难,让你的测试专注于授权,而不是承载令牌的表示。我们现在来看其中的两种:

jwt() RequestPostProcessor

第一种方式是通过 jwt RequestPostProcessor。最简单的方式如下所示:

mvc
.perform(get("/endpoint").with(jwt()));

这样做会创建一个模拟的 Jwt,并将其正确传递到所有身份验证 API 中,以便您的授权机制能够对其进行验证。

默认情况下,它创建的 JWT 具有以下特征:

{
"headers" : { "alg" : "none" },
"claims" : {
"sub" : "user",
"scope" : "read"
}
}

而生成的 Jwt,如果经过测试,会以如下方式通过:

assertThat(jwt.getTokenValue()).isEqualTo("token");
assertThat(jwt.getHeaders().get("alg")).isEqualTo("none");
assertThat(jwt.getSubject()).isEqualTo("sub");

当然,这些值是可以配置的。

任何头部或声明都可以通过其对应的方法进行配置:

mvc
.perform(get("/endpoint")
.with(jwt().jwt((jwt) -> jwt.header("kid", "one").claim("iss", "https://idp.example.org"))));
mvc
.perform(get("/endpoint")
.with(jwt().jwt((jwt) -> jwt.claims((claims) -> claims.remove("scope")))));

scopescp 声明在此处的处理方式与普通持有者令牌请求中的处理方式相同。不过,你可以通过为测试提供所需的 GrantedAuthority 实例列表来轻松覆盖此默认行为:

mvc
.perform(get("/endpoint")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_messages"))));

或者,如果你有一个自定义的 JwtCollection<GrantedAuthority> 转换器,也可以用它来派生权限:

mvc
.perform(get("/endpoint")
.with(jwt().authorities(new MyConverter())));

您也可以指定一个完整的 Jwt,此时 Jwt.Builder 会非常方便:

Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.claim("scope", "read")
.build();

mvc
.perform(get("/endpoint")
.with(jwt().jwt(jwt)));

authentication() RequestPostProcessor

第二种方式是通过使用 authentication() RequestPostProcessor。本质上,你可以实例化你自己的 JwtAuthenticationToken 并在测试中提供它,如下所示:

Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.build();
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_read");
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities);

mvc
.perform(get("/endpoint")
.with(authentication(token)));

请注意,除了上述方法外,你也可以通过使用 @MockBean 注解来直接模拟 JwtDecoder bean 本身。

测试不透明令牌认证

JWTs类似,不透明令牌需要授权服务器来验证其有效性,这可能会使测试变得更加困难。为了帮助解决这个问题,Spring Security 提供了对不透明令牌的测试支持。

假设我们有一个控制器,它获取的身份验证信息是一个 BearerTokenAuthentication

@GetMapping("/endpoint")
public String foo(BearerTokenAuthentication authentication) {
return (String) authentication.getTokenAttributes().get("sub");
}

在这种情况下,我们可以通过 opaqueToken RequestPostProcessor 方法,指示 Spring Security 包含一个默认的 BearerTokenAuthentication,如下所示:

mvc
.perform(get("/endpoint").with(opaqueToken()));

这将配置关联的 MockHttpServletRequest,使其包含一个带有简单 OAuth2AuthenticatedPrincipal、属性 Map 以及已授权权限 CollectionBearerTokenAuthentication

具体来说,它将包含一个 Map,其中包含一个键值对 sub/user

assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");

以及一个仅包含一个权限 SCOPE_readCollection 权限集合:

assertThat(token.getAuthorities()).hasSize(1);
assertThat(token.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));

Spring Security 会执行必要的工作,以确保 BearerTokenAuthentication 实例可供您的控制器方法使用。

配置权限机构

在许多情况下,你的方法受到过滤器或方法安全性的保护,需要你的 Authentication 拥有特定的授予权限才能允许请求。

在这种情况下,你可以通过 authorities() 方法指定所需的授权权限:

mvc
.perform(get("/endpoint")
.with(opaqueToken()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
);

配置声明

尽管授权在所有Spring Security中相当常见,但在OAuth 2.0的情况下,我们也有属性。

例如,假设你有一个 user_id 属性,它表示用户在系统中的 ID。在控制器中,你可能会这样访问它:

@GetMapping("/endpoint")
public String foo(BearerTokenAuthentication authentication) {
String userId = (String) authentication.getTokenAttributes().get("user_id");
// ...
}

在这种情况下,您需要使用 attributes() 方法来指定该属性:

mvc
.perform(get("/endpoint")
.with(opaqueToken()
.attributes((attrs) -> attrs.put("user_id", "1234"))
)
);

附加配置

此外,还有更多方法可用于进一步配置身份验证;具体取决于您的控制器期望接收何种数据。

其中之一是 principal(OAuth2AuthenticatedPrincipal),你可以用它来配置构成 BearerTokenAuthentication 基础的完整 OAuth2AuthenticatedPrincipal 实例。

这在以下情况下非常方便:1. 拥有自己的 OAuth2AuthenticatedPrincipal 实现,或者 2. 希望指定一个不同的主体名称

例如,假设你的授权服务器使用 user_name 属性而非 sub 属性来发送主体名称。在这种情况下,你可以手动配置一个 OAuth2AuthenticatedPrincipal

Map<String, Object> attributes = Collections.singletonMap("user_name", "foo_user");
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(
(String) attributes.get("user_name"),
attributes,
AuthorityUtils.createAuthorityList("SCOPE_message:read"));

mvc
.perform(get("/endpoint")
.with(opaqueToken().principal(principal))
);

请注意,除了使用 opaqueToken() 测试支持外,您还可以通过 @MockBean 注解来模拟 OpaqueTokenIntrospector bean 本身。