Spring security - oauth2 资源服务器测试

hen*_*els 5 java spring spring-security spring-boot spring-security-oauth2

我在使用 @WebMvcTest 和 POST HTTP 方法测试 oauth2 资源服务器时遇到了一些问题。

当我不发送 csrf 令牌时,我总是收到 403 状态代码,即使我使用不记名令牌时不需要该令牌。

这是我要测试的 POST 方法。

@PostMapping("/message")
public String createMessage(@RequestBody String message) {
    return String.format("Message was created. Content: %s", message);
}

Run Code Online (Sandbox Code Playgroud)

这是我的安全配置:

http.authorizeRequests(authorizeRequests -> authorizeRequests       
   .antMatchers("/message/**")
   .hasAuthority("SCOPE_message:read")
   .anyRequest().authenticated()
).oauth2ResourceServer(oauth2ResourceServer ->               
    oauth2ResourceServer
    .jwt(withDefaults())
);
Run Code Online (Sandbox Code Playgroud)

我正在遵循spring-security示例中提供的测试。

以下测试本应通过,但由于未在请求中发送 csrf 令牌而失败。

mockMvc.perform(post("/message").content("Hello message")
    .with(jwt(jwt -> jwt.claim("scope", "message:read")))
    .andExpect(status().isOk())
    .andExpect(content().string(is("Message was created. Content: Hello message")));
Run Code Online (Sandbox Code Playgroud)

当我将 csrf 令牌添加到请求时,测试通过:

mockMvc.perform(post("/message").content("Hello message")
    .with(jwt(jwt -> jwt.claim("scope", "message:read")))
    .with(csrf()))
    .andExpect(status().isOk())
    .andExpect(content().string(is("Message was created. Content: Hello message")));
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,不需要在 POST 请求中发送 csrf 令牌。

我已经分叉了 Spring Security GitHub 存储库,此链接中提供了具有此失败测试的项目。

有没有办法让我配置我的测试,这样我就不需要在 POST 请求中发送 csrf 令牌?

Ele*_*ana 6

为了让 CSRF 过滤器检测到您正在使用 JWT 令牌,您需要将 JWT 令牌作为Authorization标头或请求参数包含在您的请求中。
您提到的测试有一个 mock JwtDecoder,这意味着您可以使用任何字符串作为标记并模拟解码后的值。
您的测试将变为:

Jwt jwt = Jwt.withTokenValue("token")
        .header("alg", "none")
        .claim("scope", "message:read")
        .build();
when(jwtDecoder.decode(anyString())).thenReturn(jwt);
mockMvc.perform(post("/message")
        .content("Hello message")
        .header("Authorization", "Bearer " + jwt.getTokenValue()))
        .andExpect(status().isOk())
        .andExpect(content().string(is("Message was created. Content: Hello message")));
Run Code Online (Sandbox Code Playgroud)

如果您没有嘲笑,JwtDecoder那么您需要检索有效的不记名令牌并将其传递到Authorization标头中。