測試 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 測試測試上述方法將需要模擬與授權伺服器的某種授權流程。當然,這將是一項艱鉅的任務,這就是 Spring Security 提供支援來移除此樣板程式碼的原因。

例如,我們可以告訴 Spring Security 使用 oidcLogin RequestPostProcessor 來包含預設的 OidcUser,如下所示

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint").with(oidcLogin()));
mvc.get("/endpoint") {
    with(oidcLogin())
}

這樣做的效果是,將關聯的 MockHttpServletRequest 組態為包含簡單 OidcIdTokenOidcUserInfo 和授權的權限 CollectionOidcUser

具體來說,它將包含一個 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")
        }
    )
}

因為 OidcUserOidcIdToken 收集其宣告。

其他組態

還有其他方法可用於進一步組態驗證;這僅取決於您的控制器期望哪些資料

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

在這種情況下,我們可以告訴 Spring Security 使用 oauth2Login RequestPostProcessor 來包含預設的 OAuth2User,如下所示

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint").with(oauth2Login()));
mvc.get("/endpoint") {
    with(oauth2Login())
}

這樣做的效果是,將關聯的 MockHttpServletRequest 組態為包含簡單屬性 Map 和授權的權限 CollectionOAuth2User

具體來說,它將包含一個具有 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 RequestPostProcessorOAuth2AuthorizedClient 新增到模擬的 OAuth2AuthorizedClientRepository

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint").with(oauth2Client("my-app")));
mvc.get("/endpoint") {
    with(
        oauth2Client("my-app")
    )
}

這樣做的效果是,建立一個 OAuth2AuthorizedClient,其中包含簡單的 ClientRegistrationOAuth2AccessToken 和資源擁有者名稱。

具體來說,它將包含一個 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")

以及一個只包含一個範圍 readOAuth2AccessToken

  • 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 驗證

為了對資源伺服器發出授權請求,您需要一個 Bearer 令牌。

如果您的資源伺服器組態為 JWT,那麼這表示 Bearer 令牌需要根據 JWT 規範進行簽署和編碼。所有這些都可能相當令人卻步,尤其是在這不是您測試重點的情況下。

幸運的是,有許多簡單的方法可以克服此困難,並讓您的測試專注於授權,而不是表示 Bearer 令牌。我們現在將介紹其中兩種方法

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

scopescp 宣告在此處的處理方式與在正常的 Bearer 令牌請求中相同。但是,只需提供您的測試所需的 GrantedAuthority 實例清單即可覆寫此行為

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint")
        .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_messages"))));
mvc.get("/endpoint") {
    with(
        jwt().authorities(SimpleGrantedAuthority("SCOPE_messages"))
    )
}

或者,如果您有自訂的 JwtCollection<GrantedAuthority> 轉換器,您也可以使用它來衍生權限

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint")
        .with(jwt().authorities(new MyConverter())));
mvc.get("/endpoint") {
    with(
        jwt().authorities(MyConverter())
    )
}

您也可以指定完整的 JwtJwt.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
}

在這種情況下,我們可以告訴 Spring Security 使用 opaqueToken RequestPostProcessor 方法來包含預設的 BearerTokenAuthentication,如下所示

  • Java

  • Kotlin

mvc
    .perform(get("/endpoint").with(opaqueToken()));
mvc.get("/endpoint") {
    with(opaqueToken())
}

這樣做的效果是,將關聯的 MockHttpServletRequest 組態為包含簡單 OAuth2AuthenticatedPrincipal、屬性 Map 和授權的權限 CollectionBearerTokenAuthentication

具體來說,它將包含一個具有 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 本身。