
本文探讨了在Spring Boot 3和Spring Security 6环境中,采用`XorCsrfTokenRequestAttributeHandler`进行CSRF防护时,`MockMvc`单元测试中`with(csrf())`失效的问题。文章详细介绍了该配置如何解决`WebClient`的端到端测试,同时提供了一种手动获取并注入CSRF令牌的`MockMvc`测试方案,以确保API接口在启用CSRF保护时的正确性验证。
跨站请求伪造(CSRF)是一种常见的网络攻击,Spring Security提供了强大的机制来防范此类攻击。随着Spring Boot 3和Spring Security 6的发布,CSRF处理机制也进行了一些优化和调整。为了增强安全性并更好地支持现代前端框架,Spring Security推荐使用CookieCsrfTokenRepository.withHttpOnlyFalse()配合XorCsrfTokenRequestAttributeHandler来管理CSRF令牌。
以下是典型的Spring Security 6 CSRF配置示例:
// Enable CSRF security
http.csrf { csrfConfigurer ->
// see https://docs.spring.io/spring-security/reference/5.8/migration/servlet/exploits.html#_i_am_using_angularjs_or_another_javascript_framework
val tokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse()
val delegate = XorCsrfTokenRequestAttributeHandler()
// set the name of the attribute the CsrfToken will be populated on
delegate.setCsrfRequestAttributeName("_csrf")
// Use only the handle() method of XorCsrfTokenRequestAttributeHandler and the
// default implementation of resolveCsrfTokenValue() from CsrfTokenRequestHandler
val requestHandler = CsrfTokenRequestHandler(delegate::handle)
csrfConfigurer.csrfTokenRepository(tokenRepository)
csrfConfigurer.csrfTokenRequestHandler(requestHandler)
}这种配置方式在处理真实世界的HTTP请求时表现良好,特别是在端到端测试中,能够有效防范CSRF攻击。
在使用WebClient进行端到端测试时,客户端通常需要从服务器响应中获取CSRF令牌,并在后续的修改类请求(如POST、PUT、DELETE)中将其作为请求头或请求参数发送回去。上述CSRF配置与WebClient的FilterFunction结合,能够很好地实现这一流程。当遇到4xx客户端错误时,FilterFunction会检查响应中是否存在XSRF-TOKEN cookie,如果存在,则将其提取并添加到重试请求的X-XSRF-TOKEN头部和XSRF-TOKEN cookie中。
以下是WebClient中处理CSRF令牌的FilterFunction示例:
override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> =
next.exchange(request)
.flatMap { response: ClientResponse ->
if (response.statusCode().is4xxClientError) {
val csrfCookie = response.cookies().getFirst("XSRF-TOKEN")
if (csrfCookie != null) {
val retryRequest: ClientRequest = ClientRequest.from(request)
.headers { httpHeaders -> httpHeaders.set("X-XSRF-TOKEN", csrfCookie.value) }
.cookies { cookies -> cookies.add("XSRF-TOKEN", csrfCookie.value) }
.build()
return@flatMap next.exchange(retryRequest)
}
}
Mono.just(response)
}此过滤器确保了WebClient在与启用了CSRF保护的后端服务交互时,能够自动处理令牌的传递,从而使端到端测试能够顺利通过。
然而,上述有效的CSRF配置却在MockMvc的单元测试中引发了问题。MockMvc提供了一个便捷的with(csrf())方法,用于在测试请求中模拟CSRF令牌的注入。但在Spring Security 6中,当使用XorCsrfTokenRequestAttributeHandler时,SecurityMockMvcRequestPostProcessors.csrf()(即with(csrf()))不再能够正确生成或匹配所需的CSRF令牌。这导致原本能够通过的MockMvc测试开始失败,并报告CSRF令牌不匹配的错误。
以下是典型的失败MockMvc测试示例:
@Test
fun `create tender with copyFrom null should succeed and return 201 and the uuid`() {
mockMvc
.perform(
post("/api/my/endpoint")
.param("title", "Angebot 1")
.param("copyFrom", null)
.with(user(tendererTestUsers[0]))
.with(csrf()) // 此处调用with(csrf())会导致测试失败
)
.andExpectAll(
status().isCreated,
content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON),
jsonPath("$", `is`(notNullValue()))
)
}调试显示,with(csrf())生成的CSRF令牌与服务器期望的令牌不匹配,这是由于SecurityMockMvcRequestPostProcessors.csrf当前尚未支持XorCsrfTokenRequestAttributeHandler的内部机制。
鉴于with(csrf())的局限性,目前的解决方案是在MockMvc测试中手动模拟CSRF令牌的获取和提交过程。这要求测试代码模拟浏览器或WebClient的行为,首先获取CSRF令牌,然后在需要CSRF保护的请求中手动添加。
步骤一:获取CSRF Token
首先,向Spring Security默认或自定义的CSRF端点(通常是/csrf)发送一个GET请求。这个请求会触发Spring Security生成一个新的CSRF令牌,并将其设置到响应的cookie中。
import org.springframework.mock.web.MockCookie;
import org.springframework.test.web.servlet.MvcResult;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// ...
MvcResult mvcResult = this.mockMvc.perform(get("/csrf"))
.andExpect(status().isOk()) // 确保请求成功
.andReturn();
MockCookie csrfCookie = (MockCookie) mvcResult.getResponse().getCookie("XSRF-TOKEN");
// 检查cookie是否成功获取
if (csrfCookie == null) {
throw new IllegalStateException("CSRF token cookie not found in /csrf response.");
}
String csrfTokenValue = csrfCookie.getValue();步骤二:在请求中附加CSRF Token
获取到CSRF令牌的值和cookie后,在后续需要CSRF保护的POST、PUT或DELETE请求中,手动将令牌作为X-XSRF-TOKEN头部和XSRF-TOKEN cookie添加到请求中。
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// ... 假设csrfCookie和csrfTokenValue已从步骤一获取
this.mockMvc.perform(post("/api/my/endpoint")
.header("X-XSRF-TOKEN", csrfTokenValue) // 将令牌值添加到X-XSRF-TOKEN头部
.cookie(csrfCookie) // 将整个CSRF cookie添加到请求中
.param("title", "Angebot 1")
.param("copyFrom", (String) null) // 注意:对于null参数,需要显式转换为String
.with(user(tendererTestUsers[0])) // 其他认证信息
)
.andExpect(status().isCreated()); // 验证请求成功通过这种手动方式,MockMvc测试能够正确地模拟带有CSRF令牌的请求,从而验证API接口在启用CSRF保护时的行为。
总之,虽然Spring Security 6在CSRF防护方面带来了新的挑战,但通过理解其工作原理并采用适当的测试策略,我们仍然能够有效地进行单元测试和端到端测试,确保应用的安全性。在等待MockMvc对新CSRF处理器提供原生支持的同时,手动管理CSRF令牌是当前确保测试覆盖率的有效途径。
以上就是Spring Security 6下MockMvc CSRF测试的挑战与解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号