You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3中如何结合MockMVC与CSRF进行测试?

Spring Boot 3.1.4中MockMVC测试POST接口的CSRF令牌传递方案

问题根源

你遇到的导入失败问题,是因为org.springframework.security.test下的工具类属于测试专用依赖,而你只引入了运行时的spring-boot-starter-security,这个依赖不包含测试相关的代码。

解决步骤

1. 添加正确的测试依赖

需要在构建文件中引入spring-security-test测试依赖:

Gradle 写法

testImplementation 'org.springframework.security:spring-security-test'

Maven 写法

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

注意:Spring Boot 3.x版本中,这个依赖不需要指定版本,会通过Spring Boot的依赖管理自动匹配对应版本。

2. 使用CSRF令牌处理器

添加依赖后,你之前的代码写法就可以正常工作了。csrf()后置处理器会自动生成有效的CSRF令牌,并将其添加到请求中(根据请求类型,会自动选择放在请求参数或X-XSRF-TOKEN请求头里):

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;

@AutoConfigureTestEntityManager
@SpringBootTest
@AutoConfigureMockMvc
class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void postShouldReturnOkForValidInput() throws Exception {
        mockMvc.perform(post(Endpoints.LOG)
                .with(csrf()) // 自动添加CSRF令牌
                .content("{\"key\":\"value\"}") // 替换为你的有效JSON输入
                .contentType(MediaType.APPLICATION_JSON)
        ).andExpect(status().isOk());
    }
}

补充说明

  • 如果你的接口是前后端分离的AJAX请求,Spring Security默认会检查X-XSRF-TOKEN请求头,csrf()处理器会自动生成令牌并设置到这个头里,无需额外配置。
  • 不要随意禁用CSRF保护(除非是纯后端服务且无浏览器访问场景),保持CSRF保护是Web应用的安全最佳实践。

内容的提问来源于stack exchange,提问作者Kira Resari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:50:12