此版本仍在开发中,尚未被视为稳定版本。如需最新稳定版本,请使用 Spring Security 7.0.4spring-doc.cadn.net.cn

测试 OAuth 2.0

当涉及到OAuth 2.0时,之前所涵盖的基本原则仍然适用:最终取决于你的测试方法期望SecurityContextHolder中包含什么。spring-doc.cadn.net.cn

例如,对于一个看起来像这样的控制器:spring-doc.cadn.net.cn

@GetMapping("/endpoint")
public String foo(Principal user) {
    return user.getName();
}
@GetMapping("/endpoint")
fun foo(user: Principal): String {
    return user.name
}

这与 OAuth2 无关,因此您很可能只需使用 @WithMockUser即可正常运行。spring-doc.cadn.net.cn

但,在您的控制器绑定到Spring Security的OAuth 2.0支持的一些方面的情况下,如下所示:spring-doc.cadn.net.cn

@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 的测试支持就可以派上用场了。spring-doc.cadn.net.cn

测试 OIDC 登录

使用Spring MVC Test测试上述方法需要模拟某种授权流程,与授权服务器进行交互。 这无疑是一个艰巨的任务,这也是为什么Spring Security提供了去除这种样板代码的支持。spring-doc.cadn.net.cn

例如,我们可以告诉 Spring Security 使用 oidcLogin RequestPostProcessor 包含默认值 OidcUser,如下所示:spring-doc.cadn.net.cn

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

这将配置关联的MockHttpServletRequest,使其包含一个简单的OidcUserOidcIdToken以及授权权限的OidcUserInfospring-doc.cadn.net.cn

具体地,它将包括一个OidcIdToken,其中sub声明设置为userspring-doc.cadn.net.cn

assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
assertThat(user.idToken.getClaim<String>("sub")).isEqualTo("user")

an OidcUserInfo 没有任何声明设置:spring-doc.cadn.net.cn

assertThat(user.getUserInfo().getClaims()).isEmpty();
assertThat(user.userInfo.claims).isEmpty()

并且一个包含单一权限CollectionSCOPE_read:spring-doc.cadn.net.cn

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 注解spring-doc.cadn.net.cn

此外,它还将 OidcUser 链接到一个简单的 OAuth2AuthorizedClient 实例,并将其注入到模拟的 OAuth2AuthorizedClientRepository 中。 如果您的测试 使用了 @RegisteredOAuth2AuthorizedClient 注解,这将非常有用。spring-doc.cadn.net.cn

配置权限

在许多情况下,您的方法可能受到过滤器或方法安全性的保护,并且需要您的Authentication具有某些授予的权限以允许该请求。spring-doc.cadn.net.cn

在这种情况中,您可以使用 `authorities()` 方法提供所需的授权权限:spring-doc.cadn.net.cn

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的情况下我们还有声明。spring-doc.cadn.net.cn

假设你有一个user_id声明,表示系统中的用户ID。 你可能像下面这样在控制器中访问它:spring-doc.cadn.net.cn

@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()方法来指定该声明:spring-doc.cadn.net.cn

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收集其声明。spring-doc.cadn.net.cn

附加配置

有其他方法可以进一步配置认证;具体取决于控制器预期的数据类型:spring-doc.cadn.net.cn

那最后一个选项在以下情况下非常有用: spring-doc.cadn.net.cn

  • 您有自己的OAuth2User实现,或
  • 需要更改名称属性

spring-doc.cadn.net.cn

例如,假设你的授权服务器在user_name声明中发送主体名称,而不是在sub声明中。 在这种情况下,你可以手动配置一个OidcUser:spring-doc.cadn.net.cn

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 使用场景提供了测试支持。spring-doc.cadn.net.cn

假设我们有一个控制器,获取已登录的用户为一个OAuth2Userspring-doc.cadn.net.cn

@GetMapping("/endpoint")
public String foo(@AuthenticationPrincipal OAuth2User oauth2User) {
    return oauth2User.getAttribute("sub");
}
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): String? {
    return oauth2User.getAttribute("sub")
}

在这种情况下,我们可以告诉 Spring Security 使用 oauth2Login RequestPostProcessor 来包含默认的 OAuth2User,如下所示:spring-doc.cadn.net.cn

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

这将会配置关联的MockHttpServletRequest,使其包含一个简单的OAuth2User形式的属性和一个授予权限的Map,并附带一个Collectionspring-doc.cadn.net.cn

具体地,它将包含一个Map,其中包含键/值对sub:spring-doc.cadn.net.cn

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

并且一个包含单一权限CollectionSCOPE_read:spring-doc.cadn.net.cn

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 注解spring-doc.cadn.net.cn

此外,它还将 OAuth2User 链接到其存入模拟 OAuth2AuthorizedClientRepository 中的简单 OAuth2AuthorizedClient 实例。 如果您的测试 使用了 @RegisteredOAuth2AuthorizedClient 注解,这将非常有用。spring-doc.cadn.net.cn

配置权限

在许多情况下,您的方法可能受到过滤器或方法安全性的保护,并且需要您的Authentication具有某些授予的权限以允许该请求。spring-doc.cadn.net.cn

在这种情况中,您可以使用 `authorities()` 方法提供所需的授权权限:spring-doc.cadn.net.cn

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的情况下我们还有声明。spring-doc.cadn.net.cn

假设你有一个user_id属性,这个属性表示你在系统中的用户ID。 你可以在控制器中这样访问它:spring-doc.cadn.net.cn

@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()方法指定该属性:spring-doc.cadn.net.cn

mvc
    .perform(get("/endpoint")
        .with(oauth2Login()
                .attributes(attrs -> attrs.put("user_id", "1234"))
        )
    );
mvc.get("/endpoint") {
    with(oauth2Login()
        .attributes { attrs -> attrs["user_id"] = "1234" }
    )
}

附加配置

有其他方法可以进一步配置认证;具体取决于控制器预期的数据类型:spring-doc.cadn.net.cn

  • clientRegistration(ClientRegistration) - 用于配置与给定的OAuth2AuthorizedClient关联的ClientRegistrationspring-doc.cadn.net.cn

  • oauth2User(OAuth2User) - 用于配置完整的 OAuth2User 实例spring-doc.cadn.net.cn

那最后一个选项在以下情况下非常有用: spring-doc.cadn.net.cn

  • 您有自己的OAuth2User实现,或
  • 需要更改名称属性

spring-doc.cadn.net.cn

例如,假设你的授权服务器在user_name声明中发送主体名称,而不是在sub声明中。 在这种情况下,你可以手动配置一个OAuth2User:spring-doc.cadn.net.cn

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 客户端

无论用户是以何种方式进行身份验证的,您可能还需要为正在测试的请求考虑其他Tokens和客户端注册。 例如,您的控制器可能会依赖于客户端凭证授权来获取一个与该用户完全无关的Tokens:spring-doc.cadn.net.cn

@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 RequestPostProcessorOAuth2AuthorizedClient 添加到模拟的 OAuth2AuthorizedClientRepository 中:spring-doc.cadn.net.cn

mvc
    .perform(get("/endpoint").with(oauth2Client("my-app")));
mvc.get("/endpoint") {
    with(
        oauth2Client("my-app")
    )
}

这将会创建一个带有简单OAuth2AuthorizedClientClientRegistration和资源所有者名称的OAuth2AccessTokenspring-doc.cadn.net.cn

具体地,它将包含一个ClientRegistration,其客户端ID为"test-client",客户端密钥为"test-secret":spring-doc.cadn.net.cn

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

a resource owner name of "user":spring-doc.cadn.net.cn

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

并且一个仅包含一个范围OAuth2AccessTokenread:spring-doc.cadn.net.cn

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 在控制器方法中获取。spring-doc.cadn.net.cn

配置作用域

在许多情况下,OAuth 2.0 访问Tokens会包含一组作用域。 如果您的控制器检查这些内容,例如这样:spring-doc.cadn.net.cn

@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() 方法配置范围:spring-doc.cadn.net.cn

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

附加配置

有其他方法可以进一步配置认证;具体取决于控制器预期的数据类型:spring-doc.cadn.net.cn

那最后一个非常方便,如果你想要使用一个真实的ClientRegistrationspring-doc.cadn.net.cn

例如,假设您想要使用应用程序的ClientRegistration定义,该定义在您的application.yml中指定。spring-doc.cadn.net.cn

在这种情况下,你的测试可以使用@Autowired 注入 ClientRegistrationRepository 并查找测试所需的那个项:spring-doc.cadn.net.cn

@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 身份验证

要对资源服务器进行授权请求,您需要一个访问Tokens。spring-doc.cadn.net.cn

如果您的资源服务器配置了JWT,那么这意味着访问Tokens需要签名并根据JWT规范进行编码。 这一切可能会让人感到很棘手,尤其是在这不是您测试的重点时。spring-doc.cadn.net.cn

有幸的是,有很多简单的方法可以解决这个问题,并使你的测试专注于授权而不是表示Tokens。 我们现在来看看其中的两种方法:spring-doc.cadn.net.cn

jwt() RequestPostProcessor

第一种方式是通过 jwt RequestPostProcessor。 其中最简单的示例如下:spring-doc.cadn.net.cn

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

这将创建一个模拟的Jwt,确保它可以通过任何身份验证API正确传递,从而使授权机制能够对其进行验证。spring-doc.cadn.net.cn

默认情况下,它创建的JWT具有以下特征:spring-doc.cadn.net.cn

{
  "headers" : { "alg" : "none" },
  "claims" : {
    "sub" : "user",
    "scope" : "read"
  }
}

并且经过测试的Jwt将会以如下方式通过验证:spring-doc.cadn.net.cn

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

这些值当然可以进行配置。spring-doc.cadn.net.cn

任何标头或声明都可以通过其相应的方法进行配置:spring-doc.cadn.net.cn

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

The scopescp 声明在这里与正常 bearer token 请求中的处理方式相同。 然而,可以通过提供你需要的GrantedAuthority 实例列表来覆盖这种默认行为:spring-doc.cadn.net.cn

mvc
    .perform(get("/endpoint")
        .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_messages"))));
mvc.get("/endpoint") {
    with(
        jwt().authorities(SimpleGrantedAuthority("SCOPE_messages"))
    )
}

或者,如果你有一个自定义的JwtCollection<GrantedAuthority>转换器,你也可以使用它来推导权限:spring-doc.cadn.net.cn

mvc
    .perform(get("/endpoint")
        .with(jwt().authorities(new MyConverter())));
mvc.get("/endpoint") {
    with(
        jwt().authorities(MyConverter())
    )
}

您也可以指定完整的 Jwt,此时 Jwt.Builder 非常有用:spring-doc.cadn.net.cn

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 并在测试中提供它,如下所示:spring-doc.cadn.net.cn

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注解来模拟@MockBean bean本身。spring-doc.cadn.net.cn

测试不透明Tokens身份验证

类似 JWTs,不透明Tokens也需要一个授权服务器来验证其有效性,这可能会使测试更加困难。 为了应对这一情况,Spring Security 提供了对不透明Tokens的测试支持。spring-doc.cadn.net.cn

让我们假设我们有一个控制器,它获取认证信息为BearerTokenAuthentication:spring-doc.cadn.net.cn

@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
}

在这种情况下,我们可以告诉 Spring Security 使用 opaqueToken RequestPostProcessor 方法包含默认值 BearerTokenAuthentication,如下所示:spring-doc.cadn.net.cn

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

这将配置关联的MockHttpServletRequest为一个BearerTokenAuthentication,其中包括一个简单的OAuth2AuthenticatedPrincipal、包含属性的Map以及被授予权限的Collectionspring-doc.cadn.net.cn

具体地,它将包含一个Map,其中包含键/值对sub:spring-doc.cadn.net.cn

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

并且一个包含单一权限CollectionSCOPE_read:spring-doc.cadn.net.cn

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 实例可供你的控制器方法使用。spring-doc.cadn.net.cn

配置权限

在许多情况下,您的方法可能受到过滤器或方法安全性的保护,并且需要您的Authentication具有某些授予的权限以允许该请求。spring-doc.cadn.net.cn

在这种情况中,您可以使用 `authorities()` 方法提供所需的授权权限:spring-doc.cadn.net.cn

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的情况下我们还有属性。spring-doc.cadn.net.cn

假设你有一个user_id属性,这个属性表示你在系统中的用户ID。 你可以在控制器中这样访问它:spring-doc.cadn.net.cn

@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()方法指定该属性:spring-doc.cadn.net.cn

mvc
    .perform(get("/endpoint")
        .with(opaqueToken()
                .attributes(attrs -> attrs.put("user_id", "1234"))
        )
    );
mvc.get("/endpoint") {
    with(opaqueToken()
        .attributes { attrs -> attrs["user_id"] = "1234" }
    )
}

附加配置

存在其他方法来进一步配置身份验证;这仅仅取决于控制器期望的数据是什么。spring-doc.cadn.net.cn

其中一个是principal(OAuth2AuthenticatedPrincipal),你可以使用它来配置底层的OAuth2AuthenticatedPrincipal实例所依赖的完整BearerTokenAuthentication实例。spring-doc.cadn.net.cn

如果您希望: 1. 拥有自己实现的OAuth2AuthenticatedPrincipal,或 2. 指定不同的主体名称spring-doc.cadn.net.cn

例如,假设你的授权服务器将主体名称发送到user_name属性而不是sub属性。 在这种情况下,你可以手动配置一个OAuth2AuthenticatedPrincipal:spring-doc.cadn.net.cn

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注解直接模拟@MockBean bean。spring-doc.cadn.net.cn