測試 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 包括一個簡單的 OidcIdTokenOidcUserInfo 以及一組被授予的許可權(Collection of granted authorities)。

具體來說,它將包含一個 sub 宣告設定為 userOidcIdToken

  • 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 中我們還有宣告(claims)。

例如,假設你有一個 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")
}

在這種情況下,我們可以使用 oauth2Login RequestPostProcessor 告訴 Spring Security 包含一個預設的 OAuth2User,就像這樣

  • Java

  • Kotlin

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

這樣做會配置相關的 MockHttpServletRequest,使其包含一個 OAuth2User,該 OAuth2User 包括一個簡單的屬性 Map 和一組被授予的許可權(Collection of granted authorities)。

具體來說,它將包含一個鍵值對為 sub/userMap

  • 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 中我們還有宣告(claims)。

例如,假設你有一個 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,它包含一個簡單的 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")

以及一個只包含一個 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 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() 方法配置 scope

  • 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 token)。

如果你的資源伺服器配置為使用 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") } }
    )
}

這裡的 scopescp 宣告的處理方式與普通持有者令牌請求中的處理方式相同。然而,只需提供你的測試所需的 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())
    )
}

你也可以指定一個完整的 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 of granted authorities)。

具體來說,它將包含一個鍵值對為 sub/userMap

  • 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 中我們還有屬性(attributes)。

例如,假設你有一個 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 本身。