最近我们为我们使用 spring 安全 3.2 的项目引入了 CSRF 保护。
启用 CSRF 后,一些单元测试失败,因为请求中不存在 csrf token 。我将一些虚拟值放入 '_csrf' 参数中,但它不起作用。
无论如何,我可以在发送请求之前(在单元测试时)获取 csrf token 吗?
最佳答案
解决这个问题的方法是:
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
...
@Test
public void testLogin() throws Exception {
this.mockMvc.perform(post("/login")
.param("username", "...")
.param("password", "...")
.with(csrf()))
.andExpect(status().isFound())
.andExpect(header().string("Location", "redirect-url-on-success-login"));
}
重要的部分是:.with(csrf())
这将添加预期的 _csrf
查询的参数。csrf()
静态方法由 spring-security-test
提供:<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>5.3.5.RELEASE / 5.4.1</version>
<scope>test</scope>
</dependency>
您的单元测试将需要以下导入才能访问它: import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
关于spring-mvc - 在 Spring 安全中启用 CSRF 保护的单元测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25605373/