测试 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 本身。