spring - 为什么@WebMvcTest 中的 POST 请求使用 permitAll() 返回 403
问题描述
我正在测试一个具有 POST 映射的控制器。这是摘录:
@RequestMapping(path = "/bookForm", method = POST)
public String saveBook(@Valid @ModelAttribute(name = "book") BookCommand bookCommand,
BindingResult bindingResult) {
// blah blah
return "redirect:/books";
}
我正在使用 Spring 安全性,所以我写了一个测试,我希望我的一些GET
映射将被未经授权的用户拒绝,但是对于这个 POST 方法,我想允许所有的。
这是一个测试配置类:
@Configuration
public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/books/**").authenticated()
.antMatchers(HttpMethod.POST, "/bookForm").permitAll()
.and()
.httpBasic();
}
}
问题是,mockMvc
对于 POST 调用,它仍然返回 4xx。这是为什么?
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = BookController.class)
@Import(SecurityTestConfig.class)
public class BookControllerIT {
@Autowired
private MockMvc mockMvc;
// ... mocks ect
@Test // <- this is ok
public void shouldNotAllowBookUpdate() throws Exception {
mockMvc.perform(get("/books/1/update")).andExpect(status().is4xxClientError());
}
@Test // <- this fails
public void shouldAllowFormHandling() throws Exception {
mockMvc.perform(post("/bookForm")).andExpect(status().isOk());
}
}
解决方案
您应该只使用一个 Mapping Annotation either @PostMapping(value="...") OR @RequestMapping(value="...",method=POST)
。还要进行以下更改TestConfig
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/bookFrom").permitAll()
.anyRequest().authenticated();
推荐阅读
- android - Jetpack Compose“最短”旋转动画
- html - Justify-content 在我的 flexbox 中停止工作,我不知道为什么
- java - 尽管在清单中启用了明文流量,Android 仍无法发送请求
- php - 如何在 Wordpress 登录 Cookie 中禁用 HTTPOnly 标记
- android - Kotlin 我的位置服务不在后台运行
- python - 如何区分包含相同文本的元素 Python Selenium
- json - 如何快速将对象转换为可序列化的 JSON
- python - 是否有为逻辑预测器选择重要特征和特征交互的功能?
- c++ - 静态 constexpr 成员变量可以引用自己的地址吗?
- c# - 如何在 OnModelCreating 中调用非静态类来播种用户身份?