Testing OAuth 2.0

在使用 OAuth 2.0 时,前面介绍的相同原则仍然适用:最终取决于受测方法预期在 SecurityContextHolder 中是什么。

When it comes to OAuth 2.0, the same principles covered earlier still apply: Ultimately, it depends on what your method under test is expecting to be in the SecurityContextHolder.

例如,对于类似这样的控制器:

For example, for a controller that looks like this:

  • Java

  • Kotlin

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

它没有任何 OAuth2 专有内容,因此您可能只需 use @WithMockUser即可。

There’s nothing OAuth2-specific about it, so you will likely be able to simply use @WithMockUser and be fine.

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

But, in cases where your controllers are bound to some aspect of Spring Security’s OAuth 2.0 support, like the following:

  • Java

  • Kotlin

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

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

then Spring Security’s test support can come in handy.

Testing OIDC Login

使用 Spring MVC Test 测试以上方法需要模拟授权服务器中的某种授权流程,这肯定是一项艰巨的任务,这就是 Spring Security 提供支持以移除此样板代码的原因。

Testing the method above with Spring MVC Test would require simulating some kind of grant flow with an authorization server. Certainly this would be a daunting task, which is why Spring Security ships with support for removing this boilerplate.

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

For example, we can tell Spring Security to include a default OidcUser using the oidcLogin RequestPostProcessor, like so:

  • Java

  • Kotlin

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

这将配置关联的 MockHttpServletRequest,其中包含 OidcUser,该用户包括一个简单的 OidcIdTokenOidcUserInfo 和已授予权限的 Collection(集合)

What this will do is configure the associated MockHttpServletRequest with an OidcUser that includes a simple OidcIdToken, OidcUserInfo, and Collection of granted authorities.

具体来说,它将包含一个 sub 值被设置为 userOidcIdToken

Specifically, it will include an OidcIdToken with a sub claim set to user:

  • Java

  • Kotlin

assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
assertThat(user.idToken.getClaim<String>("sub")).isEqualTo("user")

一个未设置任何值的 OidcUserInfo

an OidcUserInfo with no claims set:

  • Java

  • Kotlin

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

以及一个包含一个权限 SCOPE_read 的权限 Collection(集合)

and a Collection of authorities with just one authority, SCOPE_read:

  • Java

  • Kotlin

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

Spring Security 执行必要的工作以确保 OidcUser 实例对于 xref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the @AuthenticationPrincipal 注释可用。

Spring Security does the necessary work to make sure that the OidcUser instance is available for the @AuthenticationPrincipal annotation.

此外,它还将 OidcUser 链接到 OAuth2AuthorizedClient 的一个简单实例,该实例存储在模拟 OAuth2AuthorizedClientRepository 中。如果您的测试 [使用 @RegisteredOAuth2AuthorizedClient 注释,testing-oauth2-client],这可能会派上用场。

Further, it also links that OidcUser to a simple instance of OAuth2AuthorizedClient that it deposits into an mock OAuth2AuthorizedClientRepository. This can be handy if your tests testing-oauth2-client..

Configuring Authorities

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

In many circumstances, your method is protected by filter or method security and needs your Authentication to have certain granted authorities to allow the request.

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

In this case, you can supply what granted authorities you need using the authorities() method:

  • Java

  • Kotlin

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

Configuring Claims

虽然授权的权限在所有 Spring Security 中都非常常见,但在 OAuth 2.0 中我们也有声明。

And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.

例如,假设你有 user_id 声明,它指示系统中用户的 ID。你可能会在控制器中像这样访问它:

Let’s say, for example, that you’ve got a user_id claim that indicates the user’s id in your system. You might access it like so in a controller:

  • Java

  • Kotlin

@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OidcUser oidcUser) {
    String userId = oidcUser.getIdToken().getClaim("user_id");
    // ...
}
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oidcUser: OidcUser): String {
    val userId = oidcUser.idToken.getClaim<String>("user_id")
    // ...
}

在此情况下,你希望使用 idToken() 方法指定该声明:

In that case, you’d want to specify that claim with the idToken() method:

  • Java

  • Kotlin

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

因为 OidcUserOidcIdToken 收集其声明。

since OidcUser collects its claims from OidcIdToken.

Additional Configurations

另外,还有用于进一步配置身份验证的其他方法;它仅仅取决于你的控制器所期待的数据:

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:

  • userInfo(OidcUserInfo.Builder) - For configuring the OidcUserInfo instance

  • clientRegistration(ClientRegistration) - For configuring the associated OAuth2AuthorizedClient with a given ClientRegistration

  • oidcUser(OidcUser) - For configuring the complete OidcUser instance

如果你符合以下条件,最后一个方法将派上用场:1. 有自己的 OidcUser 实现,或者 2. 需要更改名称属性

That last one is handy if you: 1. Have your own implementation of OidcUser, or 2. Need to change the name attribute

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

For example, let’s say that your authorization server sends the principal name in the user_name claim instead of the sub claim. In that case, you can configure an OidcUser by hand:

  • Java

  • Kotlin

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))
    );
val oidcUser: OidcUser = DefaultOidcUser(
    AuthorityUtils.createAuthorityList("SCOPE_message:read"),
    OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
    "user_name"
)

mvc.get("/endpoint") {
    with(oidcLogin().oidcUser(oidcUser))
}

Testing OAuth 2.0 Login

[测试 OIDC 登录,测试-oidc-登录] 一样,测试 OAuth 2.0 登录面临着一个类似的虚假授予流程的挑战。正因为如此,Spring Security 还为非 OIDC 用例提供测试支持。

As with testing-oidc-login, testing OAuth 2.0 Login presents a similar challenge of mocking a grant flow. And because of that, Spring Security also has test support for non-OIDC use cases.

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

Let’s say that we’ve got a controller that gets the logged-in user as an OAuth2User:

  • Java

  • Kotlin

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

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

In that case, we can tell Spring Security to include a default OAuth2User using the oauth2Login RequestPostProcessor, like so:

  • Java

  • Kotlin

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

这将配置一个关联的 MockHttpServletRequest,其中包括一个包含属性的简单 Map 和已授予权限的 Collection

What this will do is configure the associated MockHttpServletRequest with an OAuth2User that includes a simple Map of attributes and Collection of granted authorities.

具体来说,它将包括一个包含键值对 sub/userMap

Specifically, it will include a Map with a key/value pair of sub/user:

  • Java

  • Kotlin

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

以及一个包含一个权限 SCOPE_read 的权限 Collection(集合)

and a Collection of authorities with just one authority, SCOPE_read:

  • Java

  • Kotlin

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

Spring Security 执行必要的工作以确保 OAuth2User 实例对于 xref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the @AuthenticationPrincipal 注释可用。

Spring Security does the necessary work to make sure that the OAuth2User instance is available for the @AuthenticationPrincipal annotation.

此外,它还将该 OAuth2User 链接到一个 OAuth2AuthorizedClient 的简单实例,并将其存储在虚假 OAuth2AuthorizedClientRepository 中。如果你的测试 [使用 “@RegisteredOAuth2AuthorizedClient” 注释,测试-oauth2-client] 这将非常有用。

Further, it also links that OAuth2User to a simple instance of OAuth2AuthorizedClient that it deposits in a mock OAuth2AuthorizedClientRepository. This can be handy if your tests testing-oauth2-client.

Configuring Authorities

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

In many circumstances, your method is protected by filter or method security and needs your Authentication to have certain granted authorities to allow the request.

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

In this case, you can supply what granted authorities you need using the authorities() method:

  • Java

  • Kotlin

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

Configuring Claims

虽然授权的权限在所有 Spring Security 中都非常常见,但在 OAuth 2.0 中我们也有声明。

And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.

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

Let’s say, for example, that you’ve got a user_id attribute that indicates the user’s id in your system. You might access it like so in a controller:

  • Java

  • Kotlin

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

在此情况下,你希望使用 attributes() 方法指定该属性:

In that case, you’d want to specify that attribute with the attributes() method:

  • Java

  • Kotlin

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

Additional Configurations

另外,还有用于进一步配置身份验证的其他方法;它仅仅取决于你的控制器所期待的数据:

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:

  • clientRegistration(ClientRegistration) - For configuring the associated OAuth2AuthorizedClient with a given ClientRegistration

  • oauth2User(OAuth2User) - For configuring the complete OAuth2User instance

如果你符合以下条件,最后一个方法将派上用场:1. 有自己的 OAuth2User 实现,或者 2. 需要更改名称属性

That last one is handy if you: 1. Have your own implementation of OAuth2User, or 2. Need to change the name attribute

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

For example, let’s say that your authorization server sends the principal name in the user_name claim instead of the sub claim. In that case, you can configure an OAuth2User by hand:

  • Java

  • Kotlin

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))
    );
val oauth2User: OAuth2User = DefaultOAuth2User(
    AuthorityUtils.createAuthorityList("SCOPE_message:read"),
    mapOf(Pair("user_name", "foo_user")),
    "user_name"
)

mvc.get("/endpoint") {
    with(oauth2Login().oauth2User(oauth2User))
}

Testing OAuth 2.0 Clients

无论你的用户如何进行身份验证,你可能都有其他令牌和客户端注册,它们会影响你正在测试的请求。例如,你的控制器可能依靠客户端认证授权来获取一个根本与该用户无关的令牌:

Independent of how your user authenticates, you may have other tokens and client registrations that are in play for the request you are testing. For example, your controller may be relying on the client credentials grant to get a token that isn’t associated with the user at all:

  • Java

  • Kotlin

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

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

Simulating this handshake with the authorization server could be cumbersome. Instead, you can use the oauth2Client RequestPostProcessor to add a OAuth2AuthorizedClient into a mock OAuth2AuthorizedClientRepository:

  • Java

  • Kotlin

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

执行此操作将创建具有简单的 ClientRegistrationOAuth2AccessToken 和资源所有者名称的 OAuth2AuthorizedClient

What this will do is create an OAuth2AuthorizedClient that has a simple ClientRegistration, OAuth2AccessToken, and resource owner name.

具体来说,它将包含一个客户端 ID 为“test-client”和客户端密钥为“test-secret”的 ClientRegistration

Specifically, it will include a ClientRegistration with a client id of "test-client" and client secret of "test-secret":

  • Java

  • Kotlin

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

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

a resource owner name of "user":

  • Java

  • Kotlin

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

以及仅具有一个范围 readOAuth2AccessToken

and an OAuth2AccessToken with just one scope, read:

  • Java

  • Kotlin

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

然后可以使用控制器方法中的 @RegisteredOAuth2AuthorizedClient 以正常方式检索客户端。

The client can then be retrieved as normal using @RegisteredOAuth2AuthorizedClient in a controller method.

Configuring Scopes

在很多情况下,OAuth 2.0 访问令牌会附带一组范围。如果您的控制器检查这些范围(例如):

In many circumstances, the OAuth 2.0 access token comes with a set of scopes. If your controller inspects these, say like so:

  • Java

  • Kotlin

@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();
    }
    // ...
}
@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient): String? {
    val scopes = authorizedClient.accessToken.scopes
    if (scopes.contains("message:read")) {
        return webClient.get()
            .attributes(oauth2AuthorizedClient(authorizedClient))
            .retrieve()
            .bodyToMono(String::class.java)
            .block()
    }
    // ...
}

那么您可以使用 accessToken() 方法配置范围:

then you can configure the scope using the accessToken() method:

  • Java

  • Kotlin

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

Additional Configurations

另外,还有用于进一步配置身份验证的其他方法;它仅仅取决于你的控制器所期待的数据:

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:

  • principalName(String) - For configuring the resource owner name

  • clientRegistration(Consumer<ClientRegistration.Builder>) - For configuring the associated ClientRegistration

  • clientRegistration(ClientRegistration) - For configuring the complete ClientRegistration

如果您想使用真实的 ClientRegistration,最后一个方法非常方便。

That last one is handy if you want to use a real ClientRegistration

例如,假设您想使用在 application.yml 中指定的应用程序之一的 ClientRegistration 定义。

For example, let’s say that you are wanting to use one of your app’s ClientRegistration definitions, as specified in your application.yml.

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

In that case, your test can autowire the ClientRegistrationRepository and look up the one your test needs:

  • Java

  • Kotlin

@Autowired
ClientRegistrationRepository clientRegistrationRepository;

// ...

mvc
    .perform(get("/endpoint")
        .with(oauth2Client()
            .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook"))));
@Autowired
lateinit var clientRegistrationRepository: ClientRegistrationRepository

// ...

mvc.get("/endpoint") {
    with(oauth2Client("my-app")
        .clientRegistration(clientRegistrationRepository.findByRegistrationId("facebook"))
    )
}

Testing JWT Authentication

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

In order to make an authorized request on a resource server, you need a bearer token.

如果您的资源服务器配置为使用 JWT,那么这意味着承载令牌需要根据 JWT 规范进行签名然后进行编码。所有这一切可能令人生畏,特别是当这不是您测试的重点时。

If your resource server is configured for JWTs, then this would mean that the bearer token needs to be signed and then encoded according to the JWT specification. All of this can be quite daunting, especially when this isn’t the focus of your test.

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

Fortunately, there are a number of simple ways that you can overcome this difficulty and allow your tests to focus on authorization and not on representing bearer tokens. We’ll look at two of them now:

jwt() RequestPostProcessor

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

The first way is via the jwt RequestPostProcessor. The simplest of these would look something like this:

  • Java

  • Kotlin

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

执行此操作将创建一个模拟 Jwt,将其正确传递给任何身份验证 API,以便授权机制可以使用它进行验证。

What this will do is create a mock Jwt, passing it correctly through any authentication APIs so that it’s available for your authorization mechanisms to verify.

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

By default, the JWT that it creates has the following characteristics:

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

而且如果对生成的 Jwt 进行测试,它将通过以下方式通过:

And the resulting Jwt, were it tested, would pass in the following way:

  • Java

  • Kotlin

assertThat(jwt.getTokenValue()).isEqualTo("token");
assertThat(jwt.getHeaders().get("alg")).isEqualTo("none");
assertThat(jwt.getSubject()).isEqualTo("sub");
assertThat(jwt.tokenValue).isEqualTo("token")
assertThat(jwt.headers["alg"]).isEqualTo("none")
assertThat(jwt.subject).isEqualTo("sub")

当然,这些值可以进行配置。

These values can, of course be configured.

可以使用相应的方法配置任何头或声明:

Any headers or claims can be configured with their corresponding methods:

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint")
        .with(jwt().jwt(jwt -> jwt.header("kid", "one").claim("iss", "https://idp.example.org"))));
mvc.get("/endpoint") {
    with(
        jwt().jwt { jwt -> jwt.header("kid", "one").claim("iss", "https://idp.example.org") }
    )
}
  • Java

  • Kotlin

mvc
    .perform(get("/endpoint")
        .with(jwt().jwt(jwt -> jwt.claims(claims -> claims.remove("scope")))));
mvc.get("/endpoint") {
    with(
        jwt().jwt { jwt -> jwt.claims { claims -> claims.remove("scope") } }
    )
}

在此,scopescp 声明和在正常的承载令牌请求中处理它们的方式相同。但是,只要提供测试所需的 GrantedAuthority 实例列表,就可以简单地覆盖它:

The scope and scp claims are processed the same way here as they are in a normal bearer token request. However, this can be overridden simply by providing the list of GrantedAuthority instances that you need for your test:

  • Java

  • Kotlin

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

或者,如果您有自定义的 JwtCollection<GrantedAuthority> 转换器,则还可以使用它来推导出授权:

Or, if you have a custom Jwt to Collection<GrantedAuthority> converter, you can also use that to derive the authorities:

  • Java

  • Kotlin

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

您还可以指定完整的 Jwt,而 {security-api-url}org/springframework/security/oauth2/jwt/Jwt.Builder.html[Jwt.Builder] 非常方便:

You can also specify a complete Jwt, for which {security-api-url}org/springframework/security/oauth2/jwt/Jwt.Builder.html[Jwt.Builder] comes quite handy:

  • Java

  • Kotlin

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

mvc
    .perform(get("/endpoint")
        .with(jwt().jwt(jwt)));
val jwt: Jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .claim("scope", "read")
    .build()

mvc.get("/endpoint") {
    with(
        jwt().jwt(jwt)
    )
}

authentication() RequestPostProcessor

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

The second way is by using the authentication() RequestPostProcessor. Essentially, you can instantiate your own JwtAuthenticationToken and provide it in your test, like so:

  • Java

  • Kotlin

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)));
val jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .build()
val authorities: Collection<GrantedAuthority> = AuthorityUtils.createAuthorityList("SCOPE_read")
val token = JwtAuthenticationToken(jwt, authorities)

mvc.get("/endpoint") {
    with(
        authentication(token)
    )
}

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

Note that as an alternative to these, you can also mock the JwtDecoder bean itself with a @MockBean annotation.

Testing Opaque Token Authentication

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

Similar to testing-jwt, opaque tokens require an authorization server in order to verify their validity, which can make testing more difficult. To help with that, Spring Security has test support for opaque tokens.

假设我们有一个控制器能够作为 BearerTokenAuthentication 检索验证:

Let’s say that we’ve got a controller that retrieves the authentication as a BearerTokenAuthentication:

  • Java

  • Kotlin

@GetMapping("/endpoint")
public String foo(BearerTokenAuthentication authentication) {
    return (String) authentication.getTokenAttributes().get("sub");
}
@GetMapping("/endpoint")
fun foo(authentication: BearerTokenAuthentication): String {
    return authentication.tokenAttributes["sub"] as String
}

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

In that case, we can tell Spring Security to include a default BearerTokenAuthentication using the opaqueToken RequestPostProcessor method, like so:

  • Java

  • Kotlin

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

这将执行的操作是使用 BearerTokenAuthentication 配置关联的 MockHttpServletRequest,其中包括 OAuth2AuthenticatedPrincipalMap 属性和 Collection 个已授予的权限。

What this will do is configure the associated MockHttpServletRequest with a BearerTokenAuthentication that includes a simple OAuth2AuthenticatedPrincipal, Map of attributes, and Collection of granted authorities.

具体来说,它将包括一个包含键值对 sub/userMap

Specifically, it will include a Map with a key/value pair of sub/user:

  • Java

  • Kotlin

assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
assertThat(token.tokenAttributes["sub"] as String).isEqualTo("user")

以及一个包含一个权限 SCOPE_read 的权限 Collection(集合)

and a Collection of authorities with just one authority, SCOPE_read:

  • Java

  • Kotlin

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

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

Spring Security does the necessary work to make sure that the BearerTokenAuthentication instance is available for your controller methods.

Configuring Authorities

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

In many circumstances, your method is protected by filter or method security and needs your Authentication to have certain granted authorities to allow the request.

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

In this case, you can supply what granted authorities you need using the authorities() method:

  • Java

  • Kotlin

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

Configuring Claims

虽然已授予的权限在 Spring Security 中很常见,但在 OAuth 2.0 的情况下我们也有属性。

And while granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0.

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

Let’s say, for example, that you’ve got a user_id attribute that indicates the user’s id in your system. You might access it like so in a controller:

  • Java

  • Kotlin

@GetMapping("/endpoint")
public String foo(BearerTokenAuthentication authentication) {
    String userId = (String) authentication.getTokenAttributes().get("user_id");
    // ...
}
@GetMapping("/endpoint")
fun foo(authentication: BearerTokenAuthentication): String {
    val userId = authentication.tokenAttributes["user_id"] as String
    // ...
}

在此情况下,你希望使用 attributes() 方法指定该属性:

In that case, you’d want to specify that attribute with the attributes() method:

  • Java

  • Kotlin

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

Additional Configurations

还有一些附加方法,用于进一步配置验证;它仅仅取决于您的控制器期望什么数据。

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects.

其中一个是 principal(OAuth2AuthenticatedPrincipal),您可以使用它来配置基础 BearerTokenAuthentication 的完整 OAuth2AuthenticatedPrincipal 实例

One such is principal(OAuth2AuthenticatedPrincipal), which you can use to configure the complete OAuth2AuthenticatedPrincipal instance that underlies the BearerTokenAuthentication

它很方便,如果您:1. 有自己的 OAuth2AuthenticatedPrincipal 实现,或 2. 想指定一个不同的负责人名称

It’s handy if you: 1. Have your own implementation of OAuth2AuthenticatedPrincipal, or 2. Want to specify a different principal name

例如,假设您的授权服务器在 user_name 属性中发送负责人的名称,而不是 sub 属性中。在那种情况下,您可以手动配置一个 OAuth2AuthenticatedPrincipal

For example, let’s say that your authorization server sends the principal name in the user_name attribute instead of the sub attribute. In that case, you can configure an OAuth2AuthenticatedPrincipal by hand:

  • Java

  • Kotlin

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))
    );
val attributes: Map<String, Any> = Collections.singletonMap("user_name", "foo_user")
val principal: OAuth2AuthenticatedPrincipal = DefaultOAuth2AuthenticatedPrincipal(
    attributes["user_name"] as String?,
    attributes,
    AuthorityUtils.createAuthorityList("SCOPE_message:read")
)

mvc.get("/endpoint") {
    with(opaqueToken().principal(principal))
}

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

Note that as an alternative to using opaqueToken() test support, you can also mock the OpaqueTokenIntrospector bean itself with a @MockBean annotation.