Spring 为什么@WebMvcTest中的POST请求返回403和permitAll()
我正在测试一个具有POST映射的控制器。以下是免责声明:Spring 为什么@WebMvcTest中的POST请求返回403和permitAll(),spring,spring-boot,spring-mvc,spring-security,spring-test,Spring,Spring Boot,Spring Mvc,Spring Security,Spring Test,我正在测试一个具有POST映射的控制器。以下是免责声明: @RequestMapping(path=“/bookForm”,method=POST) 公共字符串存储簿(@Valid@modeldattribute(name=“book”)BookCommand BookCommand, BindingResult(绑定结果){ //废话 返回“重定向:/books”; } 我正在使用Spring安全性,所以我编写了一个测试,我希望我的一些GET映射对于未经授权的用户将被拒绝,但是对于这个POS
@RequestMapping(path=“/bookForm”,method=POST)
公共字符串存储簿(@Valid@modeldattribute(name=“book”)BookCommand BookCommand,
BindingResult(绑定结果){
//废话
返回“重定向:/books”;
}
我正在使用Spring安全性,所以我编写了一个测试,我希望我的一些GET
映射对于未经授权的用户将被拒绝,但是对于这个POST方法,我希望允许所有这些
下面是一个测试配置类:
@配置
公共类SecurityTestConfig扩展了WebSecurity配置适配器{
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http.authorizeRequests()
.antMatchers(“/books/**”).authenticated()
.antMatchers(HttpMethod.POST,“/bookForm”).permitAll()
.及()
.httpBasic();
}
}
问题是,mockMvc
仍然为POST调用返回4xx。为什么呢
@RunWith(SpringRunner.class)
@WebMvcTest(controllers=BookController.class)
@导入(SecurityTestConfig.class)
公共类图书管理员{
@自动连线
私有MockMvc-MockMvc;
//…嘲笑等
@Test/您应该只使用一个映射注释或者@PostMapping(value=“…”)或者@RequestMapping(value=“…”,method=POST)
。在TestConfig中也要做以下更改
是的,这个csrf().disable()
成功了。我接受并投票支持你的答案。:)
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/bookFrom").permitAll()
.anyRequest().authenticated();