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

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 を使用して、デフォルトの OidcUser を含めるように Spring Security に指示できます。

  • Java

  • Kotlin

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

これにより、関連付けられた MockHttpServletRequest が、付与された権限の単純な 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 を、モック OAuth2AuthorizedClientRepository にデポジットする OAuth2AuthorizedClient の単純なインスタンスにリンクします。これは、テストで @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 の場合にもクレームがあります。

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

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 を使用してデフォルトの OAuth2User を含めるように Spring Security に指示できます。

  • Java

  • Kotlin

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

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

具体的には、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 を、モック OAuth2AuthorizedClientRepository にデポジットする OAuth2AuthorizedClient の単純なインスタンスにリンクします。これは、テストで @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 の場合にもクレームがあります。

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

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

これにより、単純な 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 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 を構成するため

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

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

その場合、テストで 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 仕様に従ってエンコードする必要があることを意味します。これはすべて、特にこれがテストの焦点ではない場合、非常に困難な場合があります。

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

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 (Javadoc)  は非常に便利です:

  • 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

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

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

Opaque トークン認証のテスト

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

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

  • Java

  • Kotlin

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

これにより、関連する 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

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

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

追加構成

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

その 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"));

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() テストサポートを使用する代わりに、OpaqueTokenIntrospector Bean 自体を @MockBean アノテーションでモックすることもできます。