代码之家  ›  专栏  ›  技术社区  ›  erotsppa

继续从spring boot示例代码中获取403禁止

  •  1
  • erotsppa  · 技术社区  · 5 年前

    我遵循了一个简单的新手指南来进行spring引导,并设置了我的第一个控制器和一些API调用。但是,我可以调用GET,但是POST总是给我403个postman和curl的错误代码。

    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors();
        }
    
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("*"));
            configuration.setAllowCredentials(true);
            configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers","Access-Control-Allow-Origin","Access-Control-Request-Method", "Access-Control-Request-Headers","Origin","Cache-Control", "Content-Type", "Authorization"));
            configuration.setAllowedMethods(Arrays.asList("DELETE", "GET", "POST", "PATCH", "PUT"));
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    

    这是我的控制器代码

    @ApiOperation(value = "Create a new order")
        @RequestMapping(value = "/orders", method = RequestMethod.POST, produces = "application/json")
        @ResponseStatus(HttpStatus.CREATED)
        public Order createOrder(
                @ApiParam(value = "New order object", required = true)
                @RequestBody Order newOrder) {
            newOrder.setSymbol(newOrder.getSymbol().toUpperCase());
            return orderRepository.save(newOrder);
        }
    

    {
        "timestamp": "2019-10-08T19:57:03.487+0000",
        "status": 403,
        "error": "Forbidden",
        "message": "Forbidden",
        "path": "/api/v1/orders"
    }
    

    我要求卷曲

    curl --location --request POST "http://localhost:8080/api/v1/orders --data "test"
    

    我知道这不是CORS的问题,我试过其他几种auth方法,它们都给出了403(不是401)

    0 回复  |  直到 5 年前
        1
  •  2
  •   Marie Alice    5 年前

    您可以尝试查看CSRF参数。

    HttpSecurity POST 403 Forbidden

    @Override
      protected void configure(HttpSecurity http) throws Exception {
        http
          .csrf().disable();
      }
    
        2
  •  2
  •   quasimodo00    5 年前

    您需要为该url授予所有人的权限:

       http
          .csrf().disable()
           and().
             authorizeRequests().
             antMatchers("/api/v1/orders").permitAll();
    

    我不知道你是不是真的需要禁用CORS。如果没有,请删除 cors.disable() 线