对于最新的稳定版本,请使用 Spring Security 6.5.3spring-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 包含默认值OidcUser使用oidcLogin RequestPostProcessor这样:spring-doc.cadn.net.cn

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

这将要做的是配置关联的MockHttpServletRequest使用OidcUser其中包括一个简单的OidcIdToken,OidcUserInfoCollection授予的权力。spring-doc.cadn.net.cn

具体来说,它将包括一个OidcIdToken使用sub声明设置为user:spring-doc.cadn.net.cn

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

OidcUserInfo未设置索赔:spring-doc.cadn.net.cn

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

Collection只有一个权限的权威,SCOPE_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

如果您满足以下条件,最后一个会很方便: 1. 拥有自己的实现OidcUser或 2.需要更改名称属性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

假设我们有一个控制器,可以将登录用户作为OAuth2User:spring-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 包含默认值OAuth2User使用oauth2Login RequestPostProcessor这样:spring-doc.cadn.net.cn

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

这将要做的是配置关联的MockHttpServletRequest使用OAuth2User其中包括一个简单的Map属性和Collection授予的权力。spring-doc.cadn.net.cn

具体来说,它将包括一个Map键/值对为sub/user:spring-doc.cadn.net.cn

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

Collection只有一个权限的权威,SCOPE_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转换为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(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

如果您满足以下条件,最后一个会很方便: 1. 拥有自己的实现OAuth2User或 2.需要更改名称属性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 RequestPostProcessor添加一个OAuth2AuthorizedClient变成模拟OAuth2AuthorizedClientRepository:spring-doc.cadn.net.cn

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

这将创建一个OAuth2AuthorizedClient这有一个简单的ClientRegistration,OAuth2AccessToken和资源所有者名称。spring-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")

资源所有者名称为“user”:spring-doc.cadn.net.cn

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

OAuth2AccessToken只需一个示波器,read: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

在这种情况下,您的测试可以自动连接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") } }
    )
}

scopescp此处的声明处理方式与普通持有者Tokens请求中的处理方式相同。 但是,只需提供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)
    )
}

请注意,作为这些的替代方法,您还可以模拟JwtDecoderbean 本身带有@MockBean注解。spring-doc.cadn.net.cn

测试不透明Tokens身份验证

JWT 类似,不透明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 包含默认值BearerTokenAuthentication使用opaqueToken RequestPostProcessor方法,如下所示:spring-doc.cadn.net.cn

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

这将要做的是配置关联的MockHttpServletRequest使用BearerTokenAuthentication其中包括一个简单的OAuth2AuthenticatedPrincipal,Map属性,以及Collection授予的权力。spring-doc.cadn.net.cn

具体来说,它将包括一个Map键/值对为sub/user:spring-doc.cadn.net.cn

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

Collection只有一个权限的权威,SCOPE_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作为BearerTokenAuthenticationspring-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()test support,你也可以模拟OpaqueTokenIntrospectorbean 本身带有@MockBean注解。spring-doc.cadn.net.cn