測試 OAuth 2.0
談到 OAuth 2.0,之前涵蓋的原則仍然適用:最終,這取決於您要測試的方法期望在 SecurityContextHolder 中包含什麼。
例如,對於如下所示的控制器
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(Principal user) {
return user.getName();
}
@GetMapping("/endpoint")
fun foo(user: Principal): String {
return user.name
}
它沒有任何 OAuth2 特有的內容,因此您可能只需使用 @WithMockUser 即可。
但是,在控制器繫結到 Spring Security OAuth 2.0 支援的某些方面(如下所示)的情況下
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OidcUser user) {
return user.getIdToken().getSubject();
}
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal user: OidcUser): String {
return user.idToken.subject
}
那麼 Spring Security 的測試支援就派上用場了。
測試 OIDC 登入
使用 Spring MVC Test 測試上述方法將需要使用授權伺服器模擬某種授權流。這無疑是一項艱鉅的任務,這就是 Spring Security 提供支援以消除此樣板程式碼的原因。
例如,我們可以透過 oidcLogin RequestPostProcessor 告訴 Spring Security 包含一個預設的 OidcUser,如下所示
-
Java
-
Kotlin
mvc
.perform(get("/endpoint").with(oidcLogin()));
mvc.get("/endpoint") {
with(oidcLogin())
}
這將配置關聯的 MockHttpServletRequest,其中包含一個 OidcUser,該 OidcUser 包含一個簡單的 OidcIdToken、OidcUserInfo 和一組授權。
具體來說,它將包含一個 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()
以及一個只包含一個許可權(SCOPE_read)的許可權 Collection
-
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 例項,並將其存入一個模擬 OAuth2AuthorizedClientRepository。如果您的測試使用 @RegisteredOAuth2AuthorizedClient 註解,這會很方便。
配置許可權
在許多情況下,您的方法受過濾器或方法安全性的保護,需要您的 Authentication 具有某些授予的許可權才能允許請求。
在這種情況下,您可以使用 authorities() 方法提供所需的授予許可權
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(oidcLogin()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
);
mvc.get("/endpoint") {
with(oidcLogin()
.authorities(SimpleGrantedAuthority("SCOPE_message:read"))
)
}
配置宣告
雖然授予許可權在所有 Spring Security 中都非常常見,但在 OAuth 2.0 的情況下,我們也有宣告。
例如,假設您有一個 user_id 宣告,它指示使用者在您系統中的 ID。您可以在控制器中像這樣訪問它
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OidcUser oidcUser) {
String userId = oidcUser.getIdToken().getClaim("user_id");
// ...
}
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oidcUser: OidcUser): String {
val userId = oidcUser.idToken.getClaim<String>("user_id")
// ...
}
在這種情況下,您需要使用 idToken() 方法指定該宣告
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(oidcLogin()
.idToken((token) -> token.claim("user_id", "1234"))
)
);
mvc.get("/endpoint") {
with(oidcLogin()
.idToken {
it.claim("user_id", "1234")
}
)
}
因為 OidcUser 從 OidcIdToken 中收集其宣告。
附加配置
還有其他方法可以進一步配置身份驗證;這完全取決於您的控制器期望什麼資料
-
userInfo(OidcUserInfo.Builder)- 用於配置OidcUserInfo例項 -
clientRegistration(ClientRegistration)- 用於使用給定的ClientRegistration配置關聯的OAuth2AuthorizedClient -
oidcUser(OidcUser)- 用於配置完整的OidcUser例項
最後一個在以下情況下很方便:1. 您有自己的 OidcUser 實現,或 2. 需要更改名稱屬性
例如,假設您的授權伺服器在 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");
mvc
.perform(get("/endpoint")
.with(oidcLogin().oidcUser(oidcUser))
);
val oidcUser: OidcUser = DefaultOidcUser(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
"user_name"
)
mvc.get("/endpoint") {
with(oidcLogin().oidcUser(oidcUser))
}
測試 OAuth 2.0 登入
與測試 OIDC 登入一樣,測試 OAuth 2.0 登入也面臨著模擬授權流的類似挑戰。正因為如此,Spring Security 也為非 OIDC 用例提供了測試支援。
假設我們有一個控制器,它將登入使用者作為 OAuth2User 獲取
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OAuth2User oauth2User) {
return oauth2User.getAttribute("sub");
}
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): String? {
return oauth2User.getAttribute("sub")
}
在這種情況下,我們可以透過 oauth2Login RequestPostProcessor 告訴 Spring Security 包含一個預設的 OAuth2User,如下所示
-
Java
-
Kotlin
mvc
.perform(get("/endpoint").with(oauth2Login()));
mvc.get("/endpoint") {
with(oauth2Login())
}
這將配置關聯的 MockHttpServletRequest,其中包含一個 OAuth2User,該 OAuth2User 包含一個簡單的屬性 Map 和一組授予許可權。
具體來說,它將包含一個鍵/值對為 sub/user 的 Map
-
Java
-
Kotlin
assertThat((String) user.getAttribute("sub")).isEqualTo("user");
assertThat(user.getAttribute<String>("sub")).isEqualTo("user")
以及一個只包含一個許可權(SCOPE_read)的許可權 Collection
-
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 例項,並將其存入一個模擬 OAuth2AuthorizedClientRepository。如果您的測試使用 @RegisteredOAuth2AuthorizedClient 註解,這會很方便。
配置許可權
在許多情況下,您的方法受過濾器或方法安全性的保護,需要您的 Authentication 具有某些授予的許可權才能允許請求。
在這種情況下,您可以使用 authorities() 方法提供所需的授予許可權
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(oauth2Login()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
);
mvc.get("/endpoint") {
with(oauth2Login()
.authorities(SimpleGrantedAuthority("SCOPE_message:read"))
)
}
配置宣告
雖然授予許可權在所有 Spring Security 中都非常常見,但在 OAuth 2.0 的情況下,我們也有宣告。
例如,假設您有一個 user_id 屬性,它指示使用者在您系統中的 ID。您可以在控制器中像這樣訪問它
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OAuth2User oauth2User) {
String userId = oauth2User.getAttribute("user_id");
// ...
}
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): String {
val userId = oauth2User.getAttribute<String>("user_id")
// ...
}
在這種情況下,您需要使用 attributes() 方法指定該屬性
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(oauth2Login()
.attributes((attrs) -> attrs.put("user_id", "1234"))
)
);
mvc.get("/endpoint") {
with(oauth2Login()
.attributes { attrs -> attrs["user_id"] = "1234" }
)
}
附加配置
還有其他方法可以進一步配置身份驗證;這完全取決於您的控制器期望什麼資料
-
clientRegistration(ClientRegistration)- 用於使用給定的ClientRegistration配置關聯的OAuth2AuthorizedClient -
oauth2User(OAuth2User)- 用於配置完整的OAuth2User例項
最後一個在以下情況下很方便:1. 您有自己的 OAuth2User 實現,或 2. 需要更改名稱屬性
例如,假設您的授權伺服器在 user_name 宣告而不是 sub 宣告中傳送主體名稱。在這種情況下,您可以手動配置 OAuth2User
-
Java
-
Kotlin
OAuth2User oauth2User = new DefaultOAuth2User(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
Collections.singletonMap("user_name", "foo_user"),
"user_name");
mvc
.perform(get("/endpoint")
.with(oauth2Login().oauth2User(oauth2User))
);
val oauth2User: OAuth2User = DefaultOAuth2User(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
mapOf(Pair("user_name", "foo_user")),
"user_name"
)
mvc.get("/endpoint") {
with(oauth2Login().oauth2User(oauth2User))
}
測試 OAuth 2.0 客戶端
無論使用者如何進行身份驗證,您正在測試的請求可能還會涉及其他令牌和客戶端註冊。例如,您的控制器可能依賴客戶端憑據授權來獲取與使用者完全無關的令牌
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
return this.webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class)
.block();
}
@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient?): String? {
return this.webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String::class.java)
.block()
}
模擬與授權伺服器的此握手可能很麻煩。相反,您可以使用 oauth2Client RequestPostProcessor 將 OAuth2AuthorizedClient 新增到模擬 OAuth2AuthorizedClientRepository 中
-
Java
-
Kotlin
mvc
.perform(get("/endpoint").with(oauth2Client("my-app")));
mvc.get("/endpoint") {
with(
oauth2Client("my-app")
)
}
這將建立一個 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 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)
.block();
}
// ...
}
@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient): String? {
val scopes = authorizedClient.accessToken.scopes
if (scopes.contains("message:read")) {
return webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String::class.java)
.block()
}
// ...
}
那麼您可以使用 accessToken() 方法配置作用域
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(oauth2Client("my-app")
.accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read"))))
)
);
mvc.get("/endpoint") {
with(oauth2Client("my-app")
.accessToken(OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read")))
)
}
附加配置
還有其他方法可以進一步配置身份驗證;這完全取決於您的控制器期望什麼資料
-
principalName(String)- 用於配置資源所有者名稱 -
clientRegistration(Consumer<ClientRegistration.Builder>)- 用於配置關聯的ClientRegistration -
clientRegistration(ClientRegistration)- 用於配置完整的ClientRegistration
最後一個在您想要使用真實的 ClientRegistration 時很方便
例如,假設您想要使用應用程式的 ClientRegistration 定義之一,如 application.yml 中指定的那樣。
在這種情況下,您的測試可以自動裝配 ClientRegistrationRepository 並查詢測試所需的那個
-
Java
-
Kotlin
@Autowired
ClientRegistrationRepository clientRegistrationRepository;
// ...
mvc
.perform(get("/endpoint")
.with(oauth2Client()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook"))));
@Autowired
lateinit var clientRegistrationRepository: ClientRegistrationRepository
// ...
mvc.get("/endpoint") {
with(oauth2Client("my-app")
.clientRegistration(clientRegistrationRepository.findByRegistrationId("facebook"))
)
}
測試 JWT 認證
為了對資源伺服器發出授權請求,您需要一個不記名令牌。
如果您的資源伺服器配置為 JWT,則這意味著不記名令牌需要根據 JWT 規範進行簽名和編碼。所有這些都可能非常令人望而生畏,尤其是在這並非您測試的重點時。
幸運的是,有許多簡單的方法可以克服這個困難,讓您的測試專注於授權,而不是表示不記名令牌。我們現在將介紹其中兩種
jwt() RequestPostProcessor
第一種方法是透過 jwt RequestPostProcessor。最簡單的示例如下
-
Java
-
Kotlin
mvc
.perform(get("/endpoint").with(jwt()));
mvc.get("/endpoint") {
with(jwt())
}
這將建立一個模擬 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
mvc
.perform(get("/endpoint")
.with(jwt().jwt((jwt) -> jwt.header("kid", "one").claim("iss", "https://idp.example.org"))));
mvc.get("/endpoint") {
with(
jwt().jwt { jwt -> jwt.header("kid", "one").claim("iss", "https://idp.example.org") }
)
}
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(jwt().jwt((jwt) -> jwt.claims((claims) -> claims.remove("scope")))));
mvc.get("/endpoint") {
with(
jwt().jwt { jwt -> jwt.claims { claims -> claims.remove("scope") } }
)
}
此處的 scope 和 scp 宣告的處理方式與在正常不記名令牌請求中的處理方式相同。但是,只需提供測試所需的 GrantedAuthority 例項列表即可覆蓋此行為
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_messages"))));
mvc.get("/endpoint") {
with(
jwt().authorities(SimpleGrantedAuthority("SCOPE_messages"))
)
}
或者,如果您有自定義的 Jwt 到 Collection<GrantedAuthority> 轉換器,您也可以使用它來派生許可權
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(jwt().authorities(new MyConverter())));
mvc.get("/endpoint") {
with(
jwt().authorities(MyConverter())
)
}
您還可以指定完整的 Jwt,為此,Jwt.Builder 非常方便
-
Java
-
Kotlin
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.claim("scope", "read")
.build();
mvc
.perform(get("/endpoint")
.with(jwt().jwt(jwt)));
val jwt: Jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.claim("scope", "read")
.build()
mvc.get("/endpoint") {
with(
jwt().jwt(jwt)
)
}
authentication() RequestPostProcessor
第二種方法是使用 authentication() RequestPostProcessor。本質上,您可以例項化自己的 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);
mvc
.perform(get("/endpoint")
.with(authentication(token)));
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)
mvc.get("/endpoint") {
with(
authentication(token)
)
}
請注意,作為這些方法的替代,您還可以使用 @MockBean 註解模擬 JwtDecoder bean 本身。
測試不透明令牌認證
與JWT類似,不透明令牌需要授權伺服器來驗證其有效性,這可能會使測試更加困難。為了幫助解決這個問題,Spring Security 提供了對不透明令牌的測試支援。
假設我們有一個控制器,它將認證作為 BearerTokenAuthentication 檢索
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(BearerTokenAuthentication authentication) {
return (String) authentication.getTokenAttributes().get("sub");
}
@GetMapping("/endpoint")
fun foo(authentication: BearerTokenAuthentication): String {
return authentication.tokenAttributes["sub"] as String
}
在這種情況下,我們可以透過 opaqueToken RequestPostProcessor 方法告訴 Spring Security 包含一個預設的 BearerTokenAuthentication,如下所示
-
Java
-
Kotlin
mvc
.perform(get("/endpoint").with(opaqueToken()));
mvc.get("/endpoint") {
with(opaqueToken())
}
這將配置關聯的 MockHttpServletRequest,其中包含一個 BearerTokenAuthentication,該 BearerTokenAuthentication 包含一個簡單的 OAuth2AuthenticatedPrincipal、屬性 Map 和授予許可權 Collection。
具體來說,它將包含一個鍵/值對為 sub/user 的 Map
-
Java
-
Kotlin
assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
assertThat(token.tokenAttributes["sub"] as String).isEqualTo("user")
以及一個只包含一個許可權(SCOPE_read)的許可權 Collection
-
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
mvc
.perform(get("/endpoint")
.with(opaqueToken()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
);
mvc.get("/endpoint") {
with(opaqueToken()
.authorities(SimpleGrantedAuthority("SCOPE_message:read"))
)
}
配置宣告
雖然授權許可權在所有 Spring Security 中都非常常見,但在 OAuth 2.0 的情況下,我們也有屬性。
例如,假設您有一個 user_id 屬性,它指示使用者在您系統中的 ID。您可以在控制器中像這樣訪問它
-
Java
-
Kotlin
@GetMapping("/endpoint")
public String foo(BearerTokenAuthentication authentication) {
String userId = (String) authentication.getTokenAttributes().get("user_id");
// ...
}
@GetMapping("/endpoint")
fun foo(authentication: BearerTokenAuthentication): String {
val userId = authentication.tokenAttributes["user_id"] as String
// ...
}
在這種情況下,您需要使用 attributes() 方法指定該屬性
-
Java
-
Kotlin
mvc
.perform(get("/endpoint")
.with(opaqueToken()
.attributes((attrs) -> attrs.put("user_id", "1234"))
)
);
mvc.get("/endpoint") {
with(opaqueToken()
.attributes { attrs -> attrs["user_id"] = "1234" }
)
}
附加配置
還有其他方法可以進一步配置身份驗證;這完全取決於您的控制器期望什麼資料。
其中之一是 principal(OAuth2AuthenticatedPrincipal),您可以使用它來配置 BearerTokenAuthentication 底層完整的 OAuth2AuthenticatedPrincipal 例項
如果以下情況,它會很方便:1. 您有自己的 OAuth2AuthenticatedPrincipal 實現,或 2. 想要指定不同的主體名稱
例如,假設您的授權伺服器在 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"));
mvc
.perform(get("/endpoint")
.with(opaqueToken().principal(principal))
);
val attributes: Map<String, Any> = Collections.singletonMap("user_name", "foo_user")
val principal: OAuth2AuthenticatedPrincipal = DefaultOAuth2AuthenticatedPrincipal(
attributes["user_name"] as String?,
attributes,
AuthorityUtils.createAuthorityList("SCOPE_message:read")
)
mvc.get("/endpoint") {
with(opaqueToken().principal(principal))
}
請注意,作為使用 opaqueToken() 測試支援的替代方法,您還可以使用 @MockBean 註解模擬 OpaqueTokenIntrospector bean 本身。