最新の安定バージョンについては、Spring Security 6.3.1 を使用してください!

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 には、このボイラープレートを削除するためのサポートが付属しています。

例: 次のように、Spring Security に SecurityMockServerConfigurers#mockOidcLogin メソッドを使用してデフォルトの OidcUser を含めるように指示できます。

  • Java

  • Kotlin

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

これにより、関連付けられた MockServerRequest が、付与された権限の単純な OidcIdTokenOidcUserInfoCollection を含む OidcUser で構成されます。

具体的には、sub クレームが user に設定された OidcIdToken が含まれます。

  • 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 という 1 つの権限を持つ 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 の場合にもクレームがあります。

たとえば、システムのユーザー ID を示す user_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() メソッドでそのクレームを指定する必要があります。

  • 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 から収集するため。

追加構成

認証をさらに構成するための追加の方法もあります。それは単にコントローラーが期待するデータに依存します:

  • userInfo(OidcUserInfo.Builder) - OidcUserInfo インスタンスを構成するため

  • clientRegistration(ClientRegistration) - 関連する OAuth2AuthorizedClient を特定の ClientRegistration で構成するため

  • oidcUser(OidcUser) - 完全な OidcUser インスタンスを構成するため

最後の 1 つは、次の場合に便利です。1. OidcUser の独自の実装がある、または 2. 名前属性を変更する必要がある

例: 認可サーバーが、sub クレームではなく user_name クレームでプリンシパル名を送信するとします。その場合は、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#mockOAuth2Login メソッドを使用してデフォルトの OAuth2User を含めるように Spring Security に指示できます。

  • Java

  • Kotlin

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

これにより、属性の単純な Map と許可された権限の Collection を含む OAuth2User を使用して、関連付けられた MockServerRequest が構成されます。

具体的には、sub/user のキー / 値ペアを持つ Map が含まれます。

  • Java

  • Kotlin

assertThat((String) user.getAttribute("sub")).isEqualTo("user");
assertThat(user.getAttribute<String>("sub")).isEqualTo("user")

そして、SCOPE_read という 1 つの権限を持つ 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 を、モック ServerOAuth2AuthorizedClientRepository にデポジットする OAuth2AuthorizedClient の単純なインスタンスにリンクします。これは、テストで @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 の場合にもクレームがあります。

たとえば、システムのユーザー ID を示す user_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) - 関連する OAuth2AuthorizedClient を特定の ClientRegistration で構成するため

  • oauth2User(OAuth2User) - 完全な OAuth2User インスタンスを構成するため

最後の 1 つは、次の場合に便利です。1. OAuth2User の独自の実装がある、または 2. 名前属性を変更する必要がある

例: 認可サーバーが、sub クレームではなく user_name クレームでプリンシパル名を送信するとします。その場合は、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#mockOAuth2Client を使用して OAuth2AuthorizedClient をモック ServerOAuth2AuthorizedClientRepository に追加できます。

  • Java

  • Kotlin

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

これにより、単純な ClientRegistrationOAuth2AccessToken、リソース所有者名を持つ OAuth2AuthorizedClient が作成されます。

具体的には、クライアント 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")

「ユーザー」のリソース所有者名:

  • Java

  • Kotlin

assertThat(authorizedClient.getPrincipalName()).isEqualTo("user");
assertThat(authorizedClient.principalName).isEqualTo("user")

スコープが 1 つだけの OAuth2AccessToken  read:

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

次に、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()

追加構成

認証をさらに構成するための追加の方法もあります。それは単にコントローラーが期待するデータに依存します:

  • principalName(String) - リソース所有者名を構成するため

  • clientRegistration(Consumer<ClientRegistration.Builder>) - 関連する ClientRegistration を構成するため

  • clientRegistration(ClientRegistration) - 完全な ClientRegistration を構成するため

最後の 1 つは、実際の ClientRegistration を使用する場合に便利です。

例: application.yml で指定されている、アプリの ClientRegistration 定義の 1 つを使用するとします。

その場合、テストで 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 認証のテスト

リソースサーバーで承認されたリクエストを行うには、ベアラートークンが必要です。リソースサーバーが JWT 用に構成されている場合、これはベアラトークンに署名し、JWT 仕様に従ってエンコードする必要があることを意味します。これはすべて、特にテストの焦点ではない場合は非常に困難です。

幸いなことに、この困難を克服し、テストでベアラトークンの表現ではなく認証に焦点を当てることができるいくつかの簡単な方法があります。次に、そのうちの 2 つを見ていきます。

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

scope および scp クレームは、通常のベアラートークンリクエストの場合と同じようにここで処理されます。ただし、これは、テストに必要な 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 (Javadoc)  は非常に便利です:

  • 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

2 番目の方法は、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()

これらの代替として、ReactiveJwtDecoder Bean 自体を @MockBean アノテーションでモックすることもできます。

Opaque トークン認証のテスト

JWT と同様に、Opaque トークンはその有効性を検証するために認可サーバーを必要とし、テストをより困難にする可能性があります。これを支援するために、Spring Security は Opaque トークンのテストサポートを備えています。

認証を 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#mockOpaqueToken メソッドを使用してデフォルトの BearerTokenAuthentication を含めるように Spring Security に指示できます。

  • Java

  • Kotlin

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

これにより、関連する MockHttpServletRequest が、単純な OAuth2AuthenticatedPrincipal、属性の Map、許可された権限の Collection を含む BearerTokenAuthentication で構成されます。

具体的には、sub/user のキー / 値ペアを持つ Map が含まれます。

  • Java

  • Kotlin

assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
assertThat(token.tokenAttributes["sub"] as String?).isEqualTo("user")

そして、SCOPE_read という 1 つの権限を持つ 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

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 の場合にも属性があります。

たとえば、システムのユーザー ID を示す user_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()

追加構成

認証をさらに構成するための追加の方法もあります。それは単にコントローラーが期待するデータに依存します。

その 1 つが principal(OAuth2AuthenticatedPrincipal) です。これを使用して、BearerTokenAuthentication の基礎となる完全な OAuth2AuthenticatedPrincipal インスタンスを構成できます。

次の場合に便利です: 1. OAuth2AuthenticatedPrincipal の独自の実装がある、または 2. 別のプリンシパル名を指定する

例: 認可サーバーが sub 属性ではなく user_name 属性でプリンシパル名を送信するとします。その場合は、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() テストサポートを使用する代わりに、OpaqueTokenIntrospector Bean 自体を @MockBean アノテーションでモックすることもできます。