为什么@WebMvcTest中的POST请求返回带有allowAll()的403

时间:2019-05-17 04:57:15

标签: spring-boot spring-mvc spring-test spring-test-mvc

我正在测试具有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仍返回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());
    }
}

1 个答案:

答案 0 :(得分:3)

您应仅使用一个映射注释either @PostMapping(value="...") OR @RequestMapping(value="...",method=POST)。在TestConfig

中也进行以下更改
http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers(HttpMethod.POST,"/bookFrom").permitAll()  
         .anyRequest().authenticated();