对于最新的稳定版本,请使用 Spring Security 6.5.0spring-doc.cadn.net.cn

测试 OAuth 2.0

当谈到 OAuth 2.0 时,前面介绍的相同原则仍然适用:最终,这取决于你被测试的方法在SecurityContextHolder.spring-doc.cadn.net.cn

例如,对于如下所示的控制器:spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

但是,如果您的控制器绑定到 Spring Security 的 OAuth 2.0 支持的某些方面,如下所示:spring-doc.cadn.net.cn

@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 的 test 支持就可以派上用场了。spring-doc.cadn.net.cn

测试 OIDC 登录

使用WebTestClient需要使用授权服务器模拟某种授权流。 当然,这将是一项艰巨的任务,这就是为什么 Spring Security 支持删除此样板的原因。spring-doc.cadn.net.cn

例如,我们可以告诉 Spring Security 包含一个默认的OidcUser使用SecurityMockServerConfigurers#mockOidcLogin方法,如下所示:spring-doc.cadn.net.cn

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

这将做的是配置关联的MockServerRequest替换为OidcUser这包括一个简单的OidcIdToken,OidcUserInfoCollection的授予权限。spring-doc.cadn.net.cn

具体来说,它将包括一个OidcIdToken替换为subclaim 设置为user:spring-doc.cadn.net.cn

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

OidcUserInfo未设置索赔:spring-doc.cadn.net.cn

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

以及Collection只有一个授权的授权,SCOPE_read:spring-doc.cadn.net.cn

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注解.spring-doc.cadn.net.cn

此外,它还将OidcUser更改为OAuth2AuthorizedClient它存入 mock 中ServerOAuth2AuthorizedClientRepository. 如果您的测试使用@RegisteredOAuth2AuthorizedClient注解..spring-doc.cadn.net.cn

配置权限

在许多情况下,您的方法受到过滤器或方法安全性的保护,并且需要您的Authentication以授予某些权限来允许该请求。spring-doc.cadn.net.cn

在这种情况下,您可以使用authorities()方法:spring-doc.cadn.net.cn

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()

Configuring Claims

And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.spring-doc.cadn.net.cn

例如,假设您有一个user_id声明,该声明指示用户在系统中的 ID。 您可以在控制器中像这样访问它:spring-doc.cadn.net.cn

@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()方法:spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

其他配置

还有其他方法可用于进一步配置身份验证;这仅取决于您的控制者期望的数据:spring-doc.cadn.net.cn

如果您满足以下条件,最后一个选项很方便: 1. 拥有自己的OidcUser或 2. 需要更改 name 属性spring-doc.cadn.net.cn

例如,假设您的授权服务器在user_nameclaim 而不是sub索赔。 在这种情况下,您可以配置OidcUser手工:spring-doc.cadn.net.cn

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 用例提供了测试支持。spring-doc.cadn.net.cn

假设我们有一个控制器,它将登录用户作为OAuth2User:spring-doc.cadn.net.cn

@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"))
}

在这种情况下,我们可以告诉 Spring Security 包含一个默认的OAuth2User使用SecurityMockServerConfigurers#mockOAuth2Login方法,如下所示:spring-doc.cadn.net.cn

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

这将做的是配置关联的MockServerRequest替换为OAuth2User这包括一个简单的Mapof 属性和Collection的授予权限。spring-doc.cadn.net.cn

具体来说,它将包括一个Map键/值对为sub/user:spring-doc.cadn.net.cn

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

以及Collection只有一个授权的授权,SCOPE_read:spring-doc.cadn.net.cn

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注解.spring-doc.cadn.net.cn

此外,它还将OAuth2User更改为OAuth2AuthorizedClient它存放在 mock 中ServerOAuth2AuthorizedClientRepository. 如果您的测试使用@RegisteredOAuth2AuthorizedClient注解.spring-doc.cadn.net.cn

配置权限

在许多情况下,您的方法受到过滤器或方法安全性的保护,并且需要您的Authentication以授予某些权限来允许该请求。spring-doc.cadn.net.cn

在这种情况下,您可以使用authorities()方法:spring-doc.cadn.net.cn

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()

Configuring Claims

And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.spring-doc.cadn.net.cn

例如,假设您有一个user_id属性,该属性指示用户在系统中的 ID。 您可以在控制器中像这样访问它:spring-doc.cadn.net.cn

@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()方法:spring-doc.cadn.net.cn

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()

其他配置

还有其他方法可用于进一步配置身份验证;这仅取决于您的控制者期望的数据:spring-doc.cadn.net.cn

  • clientRegistration(ClientRegistration)- 用于配置关联的OAuth2AuthorizedClient使用给定的ClientRegistrationspring-doc.cadn.net.cn

  • oauth2User(OAuth2User)- 为了配置完整的OAuth2User实例spring-doc.cadn.net.cn

如果您满足以下条件,最后一个选项很方便: 1. 拥有自己的OAuth2User或 2. 需要更改 name 属性spring-doc.cadn.net.cn

例如,假设您的授权服务器在user_nameclaim 而不是sub索赔。 在这种情况下,您可以配置OAuth2User手工:spring-doc.cadn.net.cn

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 客户端

无论您的用户如何进行身份验证,您可能还有其他Tokens和客户端注册可用于您正在测试的请求。 例如,您的控制器可能依赖客户端凭证授予来获取根本不与用户关联的Tokens:spring-doc.cadn.net.cn

@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#mockOAuth2Client要添加OAuth2AuthorizedClient转换为 mockServerOAuth2AuthorizedClientRepository:spring-doc.cadn.net.cn

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

这将做的是创建一个OAuth2AuthorizedClient它有一个简单的ClientRegistration,OAuth2AccessToken和资源所有者名称。spring-doc.cadn.net.cn

具体来说,它将包括一个ClientRegistration客户端 ID 为 “test-client” 且客户端密钥为 “test-secret”:spring-doc.cadn.net.cn

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”:spring-doc.cadn.net.cn

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

以及一个OAuth2AccessToken只有一个范围,read:spring-doc.cadn.net.cn

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在 Controller 方法中。spring-doc.cadn.net.cn

配置范围

在许多情况下,OAuth 2.0 访问Tokens附带一组范围。 如果您的控制器检查这些内容,请像这样说:spring-doc.cadn.net.cn

@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()
    }
    // ...
}

然后,您可以使用accessToken()方法:spring-doc.cadn.net.cn

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()

其他配置

还有其他方法可用于进一步配置身份验证;这仅取决于您的控制者期望的数据:spring-doc.cadn.net.cn

That last one is handy if you want to use a real ClientRegistrationspring-doc.cadn.net.cn

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

In that case, your test can autowire the ReactiveClientRegistrationRepository and look up the one your test needs:spring-doc.cadn.net.cn

@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()

Testing JWT Authentication

In order to make an authorized request on a resource server, you need a bearer token. 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.spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

mockJwt() WebTestClientConfigurer

The first way is via a WebTestClientConfigurer. The simplest of these would be to use the SecurityMockServerConfigurers#mockJwt method like the following:spring-doc.cadn.net.cn

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

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.spring-doc.cadn.net.cn

By default, the JWT that it creates has the following characteristics:spring-doc.cadn.net.cn

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

And the resulting Jwt, were it tested, would pass in the following way:spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

Any headers or claims can be configured with their corresponding methods:spring-doc.cadn.net.cn

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()
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()

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:spring-doc.cadn.net.cn

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

Or, if you have a custom Jwt to Collection<GrantedAuthority> converter, you can also use that to derive the authorities:spring-doc.cadn.net.cn

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

You can also specify a complete Jwt, for which Jwt.Builder comes quite handy:spring-doc.cadn.net.cn

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

The second way is by using the authentication() Mutator. Essentially, you can instantiate your own JwtAuthenticationToken and provide it in your test, like so:spring-doc.cadn.net.cn

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()

Note that as an alternative to these, you can also mock the ReactiveJwtDecoder bean itself with a @MockBean annotation.spring-doc.cadn.net.cn

Testing Opaque Token Authentication

Similar to JWTs, 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.spring-doc.cadn.net.cn

Let’s say that we’ve got a controller that retrieves the authentication as a BearerTokenAuthentication:spring-doc.cadn.net.cn

@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?)
}

在这种情况下,我们可以告诉 Spring Security 包含一个默认的BearerTokenAuthentication使用SecurityMockServerConfigurers#mockOpaqueToken方法,如下所示:spring-doc.cadn.net.cn

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

这将做的是配置关联的MockHttpServletRequest替换为BearerTokenAuthentication这包括一个简单的OAuth2AuthenticatedPrincipal,Map of attributes, and Collection的授予权限。spring-doc.cadn.net.cn

具体来说,它将包括一个Map键/值对为sub/user:spring-doc.cadn.net.cn

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

以及Collection只有一个授权的授权,SCOPE_read:spring-doc.cadn.net.cn

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 instance is available for your controller methods.spring-doc.cadn.net.cn

配置权限

在许多情况下,您的方法受到过滤器或方法安全性的保护,并且需要您的Authentication以授予某些权限来允许该请求。spring-doc.cadn.net.cn

在这种情况下,您可以使用authorities()方法:spring-doc.cadn.net.cn

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()

Configuring Claims

And while granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0.spring-doc.cadn.net.cn

例如,假设您有一个user_id属性,该属性指示用户在系统中的 ID。 您可以在控制器中像这样访问它:spring-doc.cadn.net.cn

@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()方法:spring-doc.cadn.net.cn

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()

其他配置

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects.spring-doc.cadn.net.cn

One such is principal(OAuth2AuthenticatedPrincipal), which you can use to configure the complete OAuth2AuthenticatedPrincipal instance that underlies the BearerTokenAuthenticationspring-doc.cadn.net.cn

It’s handy if you: 1. Have your own implementation of OAuth2AuthenticatedPrincipal, or 2. Want to specify a different principal namespring-doc.cadn.net.cn

例如,假设您的授权服务器在user_name attribute instead of the sub attribute. In that case, you can configure an OAuth2AuthenticatedPrincipal手工:spring-doc.cadn.net.cn

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()

Note that as an alternative to using mockOpaqueToken() test support, you can also mock the OpaqueTokenIntrospector bean itself with a @MockBean annotation.spring-doc.cadn.net.cn