测试 OAuth 2.0

对于 OAuth 2.0,前面介绍的原理仍然适用:最终,这取决于您测试的方法期望 SecurityContextHolder 中包含什么。

考虑以下控制器示例

  • Java

  • Kotlin

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

它没有任何与 OAuth2 相关的内容,因此您可以使用 @WithMockUser,这就可以了。

然而,考虑一下您的控制器与 Spring Security 的 OAuth 2.0 支持的某个方面绑定在一起的情况

  • Java

  • Kotlin

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

在这种情况下,Spring Security 的测试支持就很有用。

测试 OIDC 登录

使用 WebTestClient 测试上一节中显示的方法需要模拟与授权服务器之间的某种授权流程。这是一项艰巨的任务,因此 Spring Security 提供了支持以消除这种繁琐的工作。

例如,我们可以通过使用 SecurityMockServerConfigurers#oidcLogin 方法告诉 Spring Security 包含一个默认的 OidcUser

  • Java

  • Kotlin

client
    .mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
client
    .mutateWith(mockOidcLogin())
    .get().uri("/endpoint")
    .exchange()

该行使用一个 OidcUser 配置关联的 MockServerRequest,该 OidcUser 包含一个简单的 OidcIdToken、一个 OidcUserInfo 和一个授权机构的 Collection

具体来说,它包含一个 OidcIdToken,其中 sub claim 设置为 user

  • Java

  • Kotlin

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

它还包含一个未设置任何 claim 的 OidcUserInfo

  • Java

  • Kotlin

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

它还包含一个只有一项授权的 Collection,即 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 实例可用于@AuthenticationPrincipal 注解

此外,它还将 OidcUser 链接到一个简单的 OAuth2AuthorizedClient 实例,并将其存入模拟的 ServerOAuth2AuthorizedClientRepository 中。如果您的测试使用 @RegisteredOAuth2AuthorizedClient 注解,这会很方便。

配置授权机构

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

在这些情况下,您可以使用 authorities() 方法提供您需要的授权机构

  • Java

  • Kotlin

client
    .mutateWith(mockOidcLogin()
        .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOidcLogin()
        .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange()

配置 Claims

虽然授权机构在 Spring Security 中很常见,但在 OAuth 2.0 的情况下,我们也有 claims。

例如,假设您有一个 user_id claim,它表示用户在您系统中的 ID。您可以在控制器中按如下方式访问它

  • Java

  • Kotlin

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

在这种情况下,您可以使用 idToken() 方法指定该 claim

  • Java

  • Kotlin

client
    .mutateWith(mockOidcLogin()
        .idToken(token -> token.claim("user_id", "1234"))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOidcLogin()
        .idToken { token -> token.claim("user_id", "1234") }
    )
    .get().uri("/endpoint").exchange()

这是因为 OidcUserOidcIdToken 中收集其 claims。

其他配置

还有其他方法,用于进一步配置认证,具体取决于您的控制器期望哪些数据

  • userInfo(OidcUserInfo.Builder):配置 OidcUserInfo 实例

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

  • oidcUser(OidcUser):配置完整的 OidcUser 实例

最后一种方法很方便,如果:* 您有自己的 OidcUser 实现 或 * 需要更改 name 属性

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

  • Java

  • Kotlin

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

client
    .mutateWith(mockOidcLogin().oidcUser(oidcUser))
    .get().uri("/endpoint").exchange();
val oidcUser: OidcUser = DefaultOidcUser(
    AuthorityUtils.createAuthorityList("SCOPE_message:read"),
    OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
    "user_name"
)

client
    .mutateWith(mockOidcLogin().oidcUser(oidcUser))
    .get().uri("/endpoint").exchange()

测试 OAuth 2.0 登录

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

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

  • Java

  • Kotlin

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

在这种情况下,我们可以通过使用 SecurityMockServerConfigurers#oauth2User 方法告诉 Spring Security 包含一个默认的 OAuth2User

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Login())
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Login())
    .get().uri("/endpoint").exchange()

前面的示例使用一个 OAuth2User 配置关联的 MockServerRequest,该 OAuth2User 包含一个简单的属性 Map 和一个授权机构的 Collection

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

  • Java

  • Kotlin

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

它还包含一个只有一项授权的 Collection,即 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 实例可用于@AuthenticationPrincipal 注解

此外,它还将该 OAuth2User 链接到一个简单的 OAuth2AuthorizedClient 实例,并将其存入模拟的 ServerOAuth2AuthorizedClientRepository 中。如果您的测试使用 @RegisteredOAuth2AuthorizedClient 注解,这会很方便。

配置授权机构

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

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

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Login()
        .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Login()
        .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange()

配置 Claims

虽然授权机构在 Spring Security 中非常常见,但在 OAuth 2.0 的情况下,我们也有 claims。

例如,假设您有一个 user_id 属性,它表示用户在您系统中的 ID。您可以在控制器中按如下方式访问它

  • Java

  • Kotlin

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

在这种情况下,您可以使用 attributes() 方法指定该属性

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Login()
        .attributes(attrs -> attrs.put("user_id", "1234"))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Login()
        .attributes { attrs -> attrs["user_id"] = "1234" }
    )
    .get().uri("/endpoint").exchange()

其他配置

还有其他方法,用于进一步配置认证,具体取决于您的控制器期望哪些数据

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

  • oauth2User(OAuth2User):配置完整的 OAuth2User 实例

最后一种方法很方便,如果:* 您有自己的 OAuth2User 实现 或 * 需要更改 name 属性

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

  • Java

  • Kotlin

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

client
    .mutateWith(mockOAuth2Login().oauth2User(oauth2User))
    .get().uri("/endpoint").exchange();
val oauth2User: OAuth2User = DefaultOAuth2User(
    AuthorityUtils.createAuthorityList("SCOPE_message:read"),
    mapOf(Pair("user_name", "foo_user")),
    "user_name"
)

client
    .mutateWith(mockOAuth2Login().oauth2User(oauth2User))
    .get().uri("/endpoint").exchange()

测试 OAuth 2.0 客户端

无论您的用户如何认证,您测试的请求中都可能涉及其他令牌和客户端注册。例如,您的控制器可能依赖于客户端凭据授权来获取与用户完全无关的令牌

  • Java

  • Kotlin

@GetMapping("/endpoint")
public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
    return this.webClient.get()
        .attributes(oauth2AuthorizedClient(authorizedClient))
        .retrieve()
        .bodyToMono(String.class);
}
import org.springframework.web.reactive.function.client.bodyToMono

// ...

@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient?): Mono<String> {
    return this.webClient.get()
        .attributes(oauth2AuthorizedClient(authorizedClient))
        .retrieve()
        .bodyToMono()
}

模拟与授权服务器的此握手可能很麻烦。取而代之的是,您可以使用 SecurityMockServerConfigurers#oauth2Client 向模拟的 ServerOAuth2AuthorizedClientRepository 中添加一个 OAuth2AuthorizedClient

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Client("my-app"))
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Client("my-app"))
    .get().uri("/endpoint").exchange()

这会创建一个 OAuth2AuthorizedClient,它具有一个简单的 ClientRegistration、一个 OAuth2AccessToken 和一个资源所有者名称。

具体来说,它包含一个 ClientRegistration,其 client ID 为 test-client,client secret 为 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

  • Java

  • Kotlin

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

它还包含一个具有一个 scope(read)的 OAuth2AccessToken

  • 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 检索客户端。

配置 Scopes

在许多情况下,OAuth 2.0 访问令牌附带一组 scopes。考虑以下控制器如何检查 scopes 的示例

  • Java

  • Kotlin

@GetMapping("/endpoint")
public Mono<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);
    }
    // ...
}
import org.springframework.web.reactive.function.client.bodyToMono

// ...

@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient): Mono<String> {
    val scopes = authorizedClient.accessToken.scopes
    if (scopes.contains("message:read")) {
        return webClient.get()
            .attributes(oauth2AuthorizedClient(authorizedClient))
            .retrieve()
            .bodyToMono()
    }
    // ...
}

给定一个检查 scopes 的控制器,您可以使用 accessToken() 方法配置 scope

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Client("my-app")
        .accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read")))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Client("my-app")
        .accessToken(OAuth2AccessToken(BEARER, "token", null, null, setOf("message:read")))
)
.get().uri("/endpoint").exchange()

其他配置

您还可以使用其他方法根据控制器期望的数据进一步配置认证

  • principalName(String):配置资源所有者名称

  • clientRegistration(Consumer<ClientRegistration.Builder>):配置关联的 ClientRegistration

  • clientRegistration(ClientRegistration):配置完整的 ClientRegistration

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

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

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

  • Java

  • Kotlin

@Autowired
ReactiveClientRegistrationRepository clientRegistrationRepository;

// ...

client
    .mutateWith(mockOAuth2Client()
        .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
    )
    .get().uri("/exchange").exchange();
@Autowired
lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository

// ...

client
    .mutateWith(mockOAuth2Client()
        .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
    )
    .get().uri("/exchange").exchange()

测试 JWT 认证

要在资源服务器上发出授权请求,需要一个 bearer 令牌。如果您的资源服务器配置为使用 JWT,则 bearer 令牌需要按照 JWT 规范进行签名和编码。所有这些可能相当令人望而生畏,特别是当这不是您测试的重点时。

幸运的是,有几种简单的方法可以克服这个困难,让您的测试专注于授权,而不是表示 bearer 令牌。我们将在接下来的两个小节中介绍其中的两种方法。

mockJwt() WebTestClientConfigurer

第一种方法是使用 WebTestClientConfigurer。其中最简单的方法是使用 SecurityMockServerConfigurers#mockJwt 方法,如下所示

  • Java

  • Kotlin

client
    .mutateWith(mockJwt()).get().uri("/endpoint").exchange();
client
    .mutateWith(mockJwt()).get().uri("/endpoint").exchange()

此示例创建一个模拟的 Jwt 并将其通过任何认证 API,以便您的授权机制可以对其进行验证。

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

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

生成的 Jwt 如果经过测试,将以下列方式通过

  • 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")

请注意,您会配置这些值。

您还可以使用相应的方法配置任何 headers 或 claims

  • Java

  • Kotlin

client
	.mutateWith(mockJwt().jwt(jwt -> jwt.header("kid", "one")
		.claim("iss", "https://idp.example.org")))
	.get().uri("/endpoint").exchange();
client
    .mutateWith(mockJwt().jwt { jwt -> jwt.header("kid", "one")
        .claim("iss", "https://idp.example.org")
    })
    .get().uri("/endpoint").exchange()
  • Java

  • Kotlin

client
	.mutateWith(mockJwt().jwt(jwt -> jwt.claims(claims -> claims.remove("scope"))))
	.get().uri("/endpoint").exchange();
client
    .mutateWith(mockJwt().jwt { jwt ->
        jwt.claims { claims -> claims.remove("scope") }
    })
    .get().uri("/endpoint").exchange()

这里的 scopescp claims 的处理方式与普通 bearer 令牌请求中的处理方式相同。然而,只需提供测试所需的 GrantedAuthority 实例列表即可覆盖此行为

  • Java

  • Kotlin

client
	.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_messages")))
	.get().uri("/endpoint").exchange();
client
    .mutateWith(mockJwt().authorities(SimpleGrantedAuthority("SCOPE_messages")))
    .get().uri("/endpoint").exchange()

另外,如果您有自定义的 JwtCollection<GrantedAuthority> 转换器,您也可以使用它来派生授权机构

  • Java

  • Kotlin

client
	.mutateWith(mockJwt().authorities(new MyConverter()))
	.get().uri("/endpoint").exchange();
client
    .mutateWith(mockJwt().authorities(MyConverter()))
    .get().uri("/endpoint").exchange()

您还可以指定一个完整的 Jwt,对此,Jwt.Builder 非常方便

  • Java

  • Kotlin

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

client
	.mutateWith(mockJwt().jwt(jwt))
	.get().uri("/endpoint").exchange();
val jwt: Jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .claim("scope", "read")
    .build()

client
    .mutateWith(mockJwt().jwt(jwt))
    .get().uri("/endpoint").exchange()

authentication()WebTestClientConfigurer

第二种方法是使用 authentication() Mutator。您可以在测试中实例化自己的 JwtAuthenticationToken 并提供它

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

client
	.mutateWith(mockAuthentication(token))
	.get().uri("/endpoint").exchange();
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)

client
    .mutateWith(mockAuthentication<JwtMutator>(token))
    .get().uri("/endpoint").exchange()

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

测试不透明令牌认证

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

假设您有一个控制器,它将认证检索为 BearerTokenAuthentication

  • Java

  • Kotlin

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

在这种情况下,您可以使用 SecurityMockServerConfigurers#opaqueToken 方法告诉 Spring Security 包含一个默认的 BearerTokenAuthentication

  • Java

  • Kotlin

client
    .mutateWith(mockOpaqueToken())
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOpaqueToken())
    .get().uri("/endpoint").exchange()

此示例使用一个 BearerTokenAuthentication 配置关联的 MockHttpServletRequest,该 BearerTokenAuthentication 包含一个简单的 OAuth2AuthenticatedPrincipal、一个属性 Map 和一个授权机构的 Collection

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

  • Java

  • Kotlin

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

它还包含一个只有一项授权的 Collection,即 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 实例可用于您的控制器方法。

配置授权机构

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

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

  • Java

  • Kotlin

client
    .mutateWith(mockOpaqueToken()
        .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOpaqueToken()
        .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange()

配置 Claims

虽然授权机构在 Spring Security 中非常常见,但在 OAuth 2.0 的情况下,我们也有 attributes。

例如,假设您有一个 user_id 属性,它表示用户在您系统中的 ID。您可以在控制器中按如下方式访问它

  • Java

  • Kotlin

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

在这种情况下,您可以使用 attributes() 方法指定该属性

  • Java

  • Kotlin

client
    .mutateWith(mockOpaqueToken()
        .attributes(attrs -> attrs.put("user_id", "1234"))
    )
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOpaqueToken()
        .attributes { attrs -> attrs["user_id"] = "1234" }
    )
    .get().uri("/endpoint").exchange()

其他配置

您还可以使用其他方法进一步配置认证,具体取决于您的控制器期望哪些数据。

其中一种方法是 principal(OAuth2AuthenticatedPrincipal),您可以使用它来配置作为 BearerTokenAuthentication 基础的完整 OAuth2AuthenticatedPrincipal 实例。

如果:* 您有自己的 OAuth2AuthenticatedPrincipal 实现 或 * 想要指定不同的主体名称,这将非常方便

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

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

client
    .mutateWith(mockOpaqueToken().principal(principal))
    .get().uri("/endpoint").exchange();
val attributes: Map<String, Any> = mapOf(Pair("user_name", "foo_user"))
val principal: OAuth2AuthenticatedPrincipal = DefaultOAuth2AuthenticatedPrincipal(
    attributes["user_name"] as String?,
    attributes,
    AuthorityUtils.createAuthorityList("SCOPE_message:read")
)

client
    .mutateWith(mockOpaqueToken().principal(principal))
    .get().uri("/endpoint").exchange()

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