測試 OAuth 2.0

當談到 OAuth 2.0 時,先前涵蓋的相同原則仍然適用:最終,這取決於您的測試方法預期 SecurityContextHolder 中會有哪些內容。

考慮以下 Controller 的範例

  • 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 即可。

然而,考慮 Controller 綁定到 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 提供支援來移除此樣板程式碼的原因。

例如,我們可以告知 Spring Security 使用 SecurityMockServerConfigurers#oidcLogin 方法來包含預設的 OidcUser

  • Java

  • Kotlin

client
    .mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
client
    .mutateWith(mockOidcLogin())
    .get().uri("/endpoint")
    .exchange()

該行程式碼使用包含簡單 OidcIdTokenOidcUserInfo 和授權許可的 CollectionOidcUser 來設定相關聯的 MockServerRequest

具體來說,它包含一個 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 的簡單實例,並將其存入模擬的 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 的情況下,我們也有聲明。

例如,假設您有一個 user_id 聲明,指示使用者在您系統中的 ID。您可以在 Controller 中如下所示存取它

  • 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()

這樣做有效,因為 OidcUserOidcIdToken 收集其聲明。

其他設定

還有其他方法可以進一步設定驗證,具體取決於您的 Controller 預期哪些資料

  • userInfo(OidcUserInfo.Builder):設定 OidcUserInfo 實例

  • clientRegistration(ClientRegistration):使用給定的 ClientRegistration 設定相關聯的 OAuth2AuthorizedClient

  • oidcUser(OidcUser):設定完整的 OidcUser 實例

如果您有以下情況,則最後一個方法很方便:* 擁有您自己的 OidcUser 實作或 * 需要變更 name 屬性

例如,假設您的授權伺服器在 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 用例提供測試支援。

假設我們有一個 Controller 將登入的使用者作為 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"))
}

在這種情況下,我們可以告知 Spring Security 使用 SecurityMockServerConfigurers#oauth2User 方法來包含預設的 OAuth2User

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Login())
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Login())
    .get().uri("/endpoint").exchange()

前面的範例使用包含簡單的屬性 Map 和授權許可 CollectionOAuth2User 來設定相關聯的 MockServerRequest

具體來說,它包含一個具有 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 的簡單實例,並將其存入模擬的 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。您可以在 Controller 中如下所示存取它

  • 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()

其他設定

還有其他方法可以進一步設定驗證,具體取決於您的 Controller 預期哪些資料

  • clientRegistration(ClientRegistration):使用給定的 ClientRegistration 設定相關聯的 OAuth2AuthorizedClient

  • oauth2User(OAuth2User):設定完整的 OAuth2User 實例

如果您有以下情況,則最後一個方法很方便:* 擁有您自己的 OAuth2User 實作或 * 需要變更 name 屬性

例如,假設您的授權伺服器在 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 Client

無論您的使用者如何驗證,您都可能有其他權杖和用戶端註冊在您正在測試的請求中發揮作用。例如,您的 Controller 可能依賴用戶端憑證授權類型來取得與使用者完全無關的權杖

  • 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#oauth2ClientOAuth2AuthorizedClient 新增至模擬的 ServerOAuth2AuthorizedClientRepository

  • Java

  • Kotlin

client
    .mutateWith(mockOAuth2Client("my-app"))
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOAuth2Client("my-app"))
    .get().uri("/endpoint").exchange()

這會建立一個 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")

然後,您可以像平常一樣在 Controller 方法中使用 @RegisteredOAuth2AuthorizedClient 檢索用戶端。

設定範圍

在許多情況下,OAuth 2.0 存取權杖都帶有一組範圍。請考慮以下 Controller 如何檢查範圍的範例

  • 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()
    }
    // ...
}

給定一個檢查範圍的 Controller,您可以使用 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()

其他設定

您也可以使用其他方法來進一步設定驗證,具體取決於您的 Controller 預期哪些資料

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

請注意,您可以設定這些值。

您也可以使用其對應的方法設定任何標頭或聲明

  • 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()

scopescp 聲明的處理方式與正常 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()

或者,如果您有自訂的 JwtCollection<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 本身。

測試 Opaque Token 驗證

JWT 類似,Opaque Token 需要授權伺服器才能驗證其有效性,這會使測試更加困難。為了幫助解決這個問題,Spring Security 為 Opaque Token 提供測試支援。

假設您有一個 Controller 將驗證檢索為 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?)
}

在這種情況下,您可以告知 Spring Security 使用 SecurityMockServerConfigurers#opaqueToken 方法來包含預設的 BearerTokenAuthentication

  • Java

  • Kotlin

client
    .mutateWith(mockOpaqueToken())
    .get().uri("/endpoint").exchange();
client
    .mutateWith(mockOpaqueToken())
    .get().uri("/endpoint").exchange()

此範例使用包含簡單的 OAuth2AuthenticatedPrincipal、屬性 Map 和授權許可 CollectionBearerTokenAuthentication 來設定相關聯的 MockHttpServletRequest

具體來說,它包含一個具有 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 實例可用於您的 Controller 方法。

設定授權許可

在許多情況下,您的方法受到過濾器或方法安全的保護,並且需要您的 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。您可以在 Controller 中如下所示存取它

  • 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()

其他設定

您也可以使用其他方法來進一步設定驗證,具體取決於您的 Controller 預期哪些資料。

其中一種方法是 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 本身。