为什么在 @WebMvcTest returns 403 中使用 permitAll() POST 请求
Why POST request in @WebMvcTest returns 403 with permitAll()
我正在测试具有 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我想允许所有的方法。
这是一个测试配置 class:
@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
仍然 returns 4xx 用于 POST 调用。这是为什么?
@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());
}
}
您应该只使用一个映射注释either @PostMapping(value="...") OR @RequestMapping(value="...",method=POST)
。还要在 TestConfig
中进行以下更改
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/bookFrom").permitAll()
.anyRequest().authenticated();
我正在测试具有 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我想允许所有的方法。
这是一个测试配置 class:
@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
仍然 returns 4xx 用于 POST 调用。这是为什么?
@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());
}
}
您应该只使用一个映射注释either @PostMapping(value="...") OR @RequestMapping(value="...",method=POST)
。还要在 TestConfig
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/bookFrom").permitAll()
.anyRequest().authenticated();