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

mate00:

我正在测试具有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());
    }
}
帕特尔·罗米尔(Patel Romil):

您应该只使用一个映射注释either @PostMapping(value="...") OR @RequestMapping(value="...",method=POST)还要在以下方面进行更改TestConfig


http
         .csrf().disable()
         .authorizeRequests()
         .antMatchers(HttpMethod.POST,"/bookFrom").permitAll()  
         .anyRequest().authenticated();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我的带有json参数和标头的HTTP POST请求返回400错误请求?

为什么来自 Unity 的 POST 请求在 php 中返回空?

为什么在Spring WebMvcTest中没有响应主体

为什么AEM对于没有扩展名的请求返回403?

为什么简单的带有axios的get请求不会返回控制器的返回值?

为什么我在Django上收到403 POST请求错误?

angularjs-为什么HTTP请求返回带有resolve的false?

为什么 POST 请求正文中的字符串带有额外的引号而不是 JSON 对象

Swift中带有键值对的POST请求

为什么我在 app.js 中的 POST 登录请求总是返回 404?

使用 WebClient 返回带有 post 请求的客户端

为什么我的 AWS Elastic Bean Stalk 节点服务器上有多个带有 /FotorShopSurpport API 的 POST 请求?

为什么POSTMAN发出的POST请求返回空?

为什么我对 PHP 文件的 Angular POST 请求返回 404?

为什么选择查询在 Athena 中返回所有带有文件数据的表数据

为什么在Kotlin中,我在带有块体错误的函数中得到“返回”表达式?

为什么对于标准内容类型的POST请求,CORS中没有预检

为什么带有后期请求的集成测试失败?

为什么我的请求总是带有空值

为什么 curl POST 请求返回的结果与此 Common Library POST 请求不同的结果到具有相同正文的相同地址?

为什么来自customTableViewCell的UiTextField在带有UITableView的UiViewController中不返回字符串

为什么每个?函数在Clojure中返回带有空向量的true?

为什么Hive SQL中带有NULL列的count(distance)返回0?

为什么从带有 querybuilder 的列中 select max 返回一个数组?

为什么通道类型中带有“ <-”?

带有查询参数的GET请求返回403错误(签名不匹配)-AWS Amplify

为什么请求不返回所有 HTML 代码

为什么网站没有收到 POST 请求?

为什么 POST 请求没有 CORS 预检检查?