測試 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()
這是因為 OidcUser
從 OidcIdToken
中收集其 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()
這裡的 scope
和 scp
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()
另外,如果您有自定義的 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()
此示例使用一個 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 本身。