Spring安全-OAuth2资源服务器测试 [英] Spring security - oauth2 resource server tests
本文介绍了Spring安全-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);
}
这是我的安全配置:
http.authorizeRequests(authorizeRequests -> authorizeRequests
.antMatchers("/message/**")
.hasAuthority("SCOPE_message:read")
.anyRequest().authenticated()
).oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer
.jwt(withDefaults())
);
我正在遵循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")));
当我向请求添加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")));
当我运行应用程序时,不需要在POST请求中发送CSRF令牌。
我已经派生了Spring Security GitHub存储库,具有此失败测试的项目可以在link上找到。
有没有办法配置我的测试,使我不需要在POST请求中发送CSRF令牌?
推荐答案
为了使CSRF筛选器检测到您正在使用JWT令牌,您需要将JWT令牌作为Authorization
头或请求参数包括在请求中。
您提到的测试有一个模拟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")));
如果您没有模拟JwtDecoder
,则需要检索有效的承载令牌并在Authorization
头中传递该令牌。
这篇关于Spring安全-OAuth2资源服务器测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文