从Spring Boot示例代码中继续获取403禁止

时间:2019-10-08 20:08:53

标签: java spring-boot http authentication

我按照新手的简单教程进行了春季启动,并设置了我的第一个控制器和一些API调用。但是,我可以调用GET,但是POST始终会给我邮递员和curl的403错误代码。

这是我的相关代码

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

这是http响应:

{
    "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问题,我尝试了其他几种身份验证方法,所有方法都给出403(而非401)

2 个答案:

答案 0 :(得分:1)

您可以尝试查看CSRF参数。

HttpSecurity POST 403 Forbidden

@Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable();
  }

答案 1 :(得分:1)

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

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

我不知道您是否真的需要禁用CORS。否则,请删除cors.disable()