对于最新的稳定版本,请使用 Spring Security 6.5.3! |
测试 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 登录
例如,我们可以告诉 Spring Security 包含默认值OidcUser
通过使用SecurityMockServerConfigurers#oidcLogin
方法:
-
Java
-
Kotlin
client
.mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
client
.mutateWith(mockOidcLogin())
.get().uri("/endpoint")
.exchange()
该行配置了关联的MockServerRequest
使用OidcUser
其中包括一个简单的OidcIdToken
一OidcUserInfo
和一个Collection
授予的权力。
具体来说,它包括一个OidcIdToken
使用sub
声明设置为user
:
-
Java
-
Kotlin
assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
assertThat(user.idToken.getClaim<String>("sub")).isEqualTo("user")
它还包括一个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()
配置声明
虽然授予的权限在所有 Spring Security 中都很常见,但我们在 OAuth 2.0 的情况下也有声明。
例如,假设您有一个user_id
声明,指示系统中的用户 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()
方法:
-
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()
之所以有效,是因为OidcUser
从OidcIdToken
.
其他配置
还有其他方法可用于进一步配置身份验证,具体取决于您的控制者期望的数据:
-
userInfo(OidcUserInfo.Builder)
:配置OidcUserInfo
实例 -
clientRegistration(ClientRegistration)
:配置关联的OAuth2AuthorizedClient
使用给定的ClientRegistration
-
oidcUser(OidcUser)
:配置完整的OidcUser
实例
如果您满足以下条件,最后一个会很方便:
* 拥有自己的实现OidcUser
或
* 需要更改名称属性
例如,假设您的授权服务器在user_name
声明而不是sub
索赔。
在这种情况下,您可以配置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"))
}
在这种情况下,我们可以告诉 Spring Security 包含默认值OAuth2User
通过使用SecurityMockServerConfigurers#oauth2User
方法:
-
Java
-
Kotlin
client
.mutateWith(mockOAuth2Login())
.get().uri("/endpoint").exchange();
client
.mutateWith(mockOAuth2Login())
.get().uri("/endpoint").exchange()
前面的示例配置了关联的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()
配置声明
虽然授予的权限在整个 Spring Security 中都很常见,但我们在 OAuth 2.0 的情况下也有声明。
例如,假设您有一个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)
:配置关联的OAuth2AuthorizedClient
使用给定的ClientRegistration
-
oauth2User(OAuth2User)
:配置完整的OAuth2User
实例
如果您满足以下条件,最后一个会很方便:
* 拥有自己的实现OAuth2User
或
* 需要更改名称属性
例如,假设您的授权服务器在user_name
声明而不是sub
索赔。
在这种情况下,您可以配置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 客户端
与用户的身份验证方式无关,您可能有其他Tokens和客户端注册正在为正在测试的请求发挥作用。例如,您的控制器可能依赖于客户端凭据授予来获取与用户完全不关联的Tokens:
-
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
添加一个OAuth2AuthorizedClient
到模拟ServerOAuth2AuthorizedClientRepository
:
-
Java
-
Kotlin
client
.mutateWith(mockOAuth2Client("my-app"))
.get().uri("/endpoint").exchange();
client
.mutateWith(mockOAuth2Client("my-app"))
.get().uri("/endpoint").exchange()
这会创建一个OAuth2AuthorizedClient
这有一个简单的ClientRegistration
一个OAuth2AccessToken
和资源所有者名称。
具体来说,它包括一个ClientRegistration
客户端 ID 为test-client
以及客户端密钥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")
它还包括一个OAuth2AccessToken
使用一个范围,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
在控制器方法中。
配置范围
在许多情况下,OAuth 2.0 访问Tokens附带一组范围。 请考虑以下示例,说明控制器如何检查范围:
-
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()
}
// ...
}
给定一个检查范围的控制器,您可以使用accessToken()
方法:
-
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 身份验证
若要在资源服务器上发出授权请求,需要持有者Tokens。 如果资源服务器配置了 JWT,则需要对持有者Tokens进行签名,然后根据 JWT 规范进行编码。 所有这些都可能非常令人生畏,尤其是当这不是测试的重点时。
幸运的是,有许多简单的方法可以克服这个困难,让你的测试专注于授权,而不是表示不记名Tokens。 我们将在接下来的两个小节中介绍其中两个。
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")
请注意,您可以配置这些值。
还可以使用其相应的方法配置任何标头或声明:
-
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()
这scope
和scp
声明的处理方式与在普通持有者Tokens请求中的处理方式相同。但是,只需提供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()
或者,如果您有自定义Jwt
自Collection<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()
请注意,作为这些的替代方法,您还可以模拟ReactiveJwtDecoder
bean 本身带有@MockBean
注解。
测试不透明Tokens身份验证
与 JWT 类似,不透明Tokens需要授权服务器来验证其有效性,这会使测试更加困难。 为了帮助解决这个问题,Spring Security 提供了对不透明Tokens的测试支持。
假设您有一个控制器,该控制器将身份验证检索为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?)
}
在这种情况下,您可以告诉 Spring Security 包含默认值BearerTokenAuthentication
通过使用SecurityMockServerConfigurers#opaqueToken
方法:
-
Java
-
Kotlin
client
.mutateWith(mockOpaqueToken())
.get().uri("/endpoint").exchange();
client
.mutateWith(mockOpaqueToken())
.get().uri("/endpoint").exchange()
此示例配置关联的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()
配置声明
虽然授予的权限在所有 Spring Security 中都很常见,但我们在 OAuth 2.0 的情况下也有属性。
例如,假设您有一个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)
,您可以使用它来配置完整的OAuth2AuthenticatedPrincipal
作为BearerTokenAuthentication
.
如果您满足以下条件,它会很方便:
* 拥有自己的实现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()
test support,你也可以模拟OpaqueTokenIntrospector
bean 本身带有@MockBean
注解。