跳到主要内容

测试 OAuth 2.0

QWen Max 中英对照 Mocking OAuth2 Testing OAuth 2.0

当涉及到 OAuth 2.0 时,前面介绍的原则仍然适用:最终,这取决于你的测试方法期望 SecurityContextHolder 中包含什么。

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

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

这没有什么是特定于OAuth2的,所以你很可能可以直接使用 @WithMockUser 就可以了。

但是在某些情况下,你的控制器绑定到了 Spring Security 的 OAuth 2.0 支持的某些方面,比如以下情况:

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

那么 Spring Security 的测试支持就可以派上用场了。

测试 OIDC 登录

使用 Spring MVC Test 测试上述方法将需要模拟某种授权流程与授权服务器。当然,这将是一项艰巨的任务,这也是为什么 Spring Security 提供了支持以消除这些样板代码。

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

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

这将会配置关联的 MockHttpServletRequest,其中包含一个具有简单 OidcIdTokenOidcUserInfo 和授权集合(Collection)的 OidcUser

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

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

一个没有设置声明的 OidcUserInfo

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

并包含一个只有一个权限 SCOPE_readCollection

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

Spring Security 执行必要的工作以确保 OidcUser 实例可用于 the @AuthenticationPrincipal 注解

此外,它还将 OidcUser 链接到一个简单的 OAuth2AuthorizedClient 实例,并将其存入一个模拟的 OAuth2AuthorizedClientRepository 中。如果你的测试使用 @RegisteredOAuth2AuthorizedClient 注解,这将非常有用。

配置Authorities

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

在这种情况下,您可以使用 authorities() 方法提供所需的授权:

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

配置声明

而虽然授予的权限在 Spring Security 中非常常见,但在 OAuth 2.0 的情况下,我们还有声明(claims)。

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

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

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

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

由于 OidcUserOidcIdToken 收集其声明。

附加配置

还有其他一些方法可以进一步配置身份验证;这仅仅取决于你的控制器期望什么样的数据。

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

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

  • 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))
);
java

测试 OAuth 2.0 登录

就像测试 OIDC 登录一样,测试 OAuth 2.0 登录也面临着类似的模拟授权流程的挑战。正因为如此,Spring Security 也为非 OIDC 用例提供了测试支持。

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

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

在这种情况下,我们可以告诉Spring Security使用 oauth2Login RequestPostProcessor 包含一个默认的 OAuth2User,如下所示:

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

这将会配置关联的 MockHttpServletRequest,其中包含一个具有简单属性 Map 和授权集合 CollectionOAuth2User

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

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

以及一个包含一个权限 SCOPE_readCollection

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

Spring Security 执行必要的工作以确保 OAuth2User 实例可用于 the @AuthenticationPrincipal 注解

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

配置权限

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

在这种情况下,你可以使用 authorities() 方法来提供你需要的授权:

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

配置声明

而在整个 Spring Security 中,授予的权限相当常见,但在 OAuth 2.0 的情况下,我们还有声明(claims)。

比如说,你有一个 user_id 属性,它表示用户在你的系统中的ID。你可以在控制器中这样访问它:

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

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

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

额外配置

还有其他方法可以进一步配置身份验证;这仅仅取决于你的控制器期望什么样的数据。

  • 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))
);
java

测试 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();
}
java

模拟与授权服务器的这种握手可能会很繁琐。相反,您可以使用 oauth2Client RequestPostProcessorOAuth2AuthorizedClient 添加到模拟的 OAuth2AuthorizedClientRepository 中:

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

这将创建一个具有简单ClientRegistrationOAuth2AccessToken和资源所有者名称的OAuth2AuthorizedClient

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

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

一个资源所有者名称为 "user":

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

以及一个仅有一个 read 范围的 OAuth2AccessToken

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

然后可以在控制器方法中使用 @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();
}
// ...
}
java

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

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

附加配置

还有其他一些方法可以进一步配置身份验证;这仅仅取决于你的控制器期望什么样的数据。

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

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

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

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

例如,假设你想要使用在 application.yml 中定义的你的应用程序的某个 ClientRegistration 定义。

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

@Autowired
ClientRegistrationRepository clientRegistrationRepository;

// ...

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

测试 JWT 身份验证

为了对资源服务器进行授权请求,你需要一个承载令牌。

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

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

jwt() RequestPostProcessor

第一种方法是通过 jwt RequestPostProcessor。其中最简单的看起来像这样:

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

这将会创建一个模拟的 Jwt,并正确地通过任何认证 API,以便你的授权机制可以进行验证。

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

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

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

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

这些值当然可以配置。

任何头部或声明都可以使用它们对应的方法进行配置:

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

scopescp 声明在这里的处理方式与在普通的承载令牌请求中的处理方式相同。但是,您可以通过提供测试所需的 GrantedAuthority 实例列表来简单地覆盖这一点:

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

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

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

您还可以指定一个完整的 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)));
java

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)));
java

请注意,作为这些方法的替代方案,您也可以使用 @MockBean 注解来模拟 JwtDecoder bean 本身。

测试不透明令牌身份验证

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

假设我们有一个控制器,它将身份验证作为 BearerTokenAuthentication 检索:

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

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

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

这将会配置关联的 MockHttpServletRequest,并使用包含一个简单的 OAuth2AuthenticatedPrincipal、属性 Map 以及授权集合 CollectionBearerTokenAuthentication

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

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

并包含一个只有一个权限 SCOPE_readCollection

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

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

配置Authorities

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

在这种情况下,您可以使用 authorities() 方法提供所需的授权:

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

配置声明

而在整个 Spring Security 中,授予的权限相当常见,但在 OAuth 2.0 的情况下,我们还有属性。

比如说,你有一个 user_id 属性,它表示用户在你的系统中的ID。你可以在控制器中这样访问它:

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

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

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

额外配置

还有其他方法可以进一步配置身份验证;这仅仅取决于你的控制器期望什么样的数据。

其中一个这样的方法是 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))
);
java

请注意,作为使用 opaqueToken() 测试支持的替代方案,您也可以使用 @MockBean 注解来模拟 OpaqueTokenIntrospector bean 本身。