测试 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()
该行配置了关联的 MockServerRequest
,其中包含一个简单的 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
实例可用于the @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 的情况下,我们还有声明(claims)。
假设,你有一个 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)
: 使用给定的ClientRegistration
配置关联的OAuth2AuthorizedClient
-
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"))
}
在这种情况下,我们可以使用 SecurityMockServerConfigurers#oauth2User
方法告诉 Spring Security 包含一个默认的 OAuth2User
:
- Java
- Kotlin
client
.mutateWith(mockOAuth2Login())
.get().uri("/endpoint").exchange();
client
.mutateWith(mockOAuth2Login())
.get().uri("/endpoint").exchange()
上述示例使用包含简单属性 Map
和授权集合 Collection
的 OAuth2User
配置了关联的 MockServerRequest
。
具体来说,它包含一个 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
实例可用于 the @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)
:使用给定的ClientRegistration
配置关联的OAuth2AuthorizedClient
-
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 客户端
无论您的用户如何进行身份验证,您正在测试的请求中可能还涉及其他令牌和客户端注册。例如,您的控制器可能依赖于客户端凭据授权来获取一个与用户完全无关的令牌:
- 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
以及资源所有者名称。
具体来说,它包含一个客户端 ID 为 test-client
和客户端密钥为 test-secret
的 ClientRegistration
:
- 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")
它还包括一个带有一个 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
来像往常一样检索客户端。
配置范围
在许多情况下,OAuth 2.0 访问令牌会附带一组范围。请考虑以下控制器如何检查这些范围的示例:
- 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
时非常方便。
例如,假设你希望使用你在 application.yml
中定义的一个应用程序的 ClientRegistration
定义。
在这种情况下,你的测试可以自动装配 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 身份验证
要对资源服务器进行授权请求,您需要一个承载令牌。如果您的资源服务器配置为使用 JWT,则承载令牌需要根据 JWT 规范进行签名并编码。所有这些可能会非常令人生畏,特别是当这不是您测试的重点时。
幸运的是,有一些简单的方法可以克服这个困难,让你的测试专注于授权而不是表示承载令牌。我们将在接下来的两个小节中介绍其中的两种方法。
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
声明在这里的处理方式与在普通的 bearer token 请求中的处理方式相同。但是,您可以通过提供测试所需的一组 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()
请注意,作为这些方法的替代,您也可以使用 @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()
此示例使用包含简单 OAuth2AuthenticatedPrincipal
、属性 Map
以及授权集合的 BearerTokenAuthentication
配置关联的 MockHttpServletRequest
。
具体来说,它包含一个 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)
,你可以使用它来配置作为 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 本身。