为什么在@webmvctest中发布请求将带有许可证()返回403



我正在测试一个具有后映射的控制器。这是摘要:

@RequestMapping(path = "/bookForm", method = POST)
public String saveBook(@Valid @ModelAttribute(name = "book") BookCommand bookCommand,
                       BindingResult bindingResult) {
        // blah blah
        return "redirect:/books";
    }

我正在使用Spring Security,所以我写了一项测试,我希望我的某些GET映射将被拒绝未经授权的用户,但是对于此帖子方法,我想允许全部。

这是一个测试配置类:

@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以获取帖子通话。为什么是?

@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();

最新更新