Spring Boot CORS 块 DELETE 请求

Spring Boot CORS blocks DELETE requests

每当我尝试使用 axios 发送删除端点的请求时,我都会收到以下错误:

从 'http://localhost:8080/api/payment_card/delete/1234123412343433' 访问 XMLHttpRequest 来源 'http://localhost:3000' 已被 CORS 策略阻止:对预检请求的响应 未通过访问控制检查:没有 'Access-Control-Allow-Origin' header 出现在 请求的资源

axios 请求构建如下:

      .delete(
        "http://localhost:8080/api/payment_card/delete/" +  selectedCardId ,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Access-Control-Allow-Origin": "**"
          },
        }
      )
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });```
My java WebSecurityConfig stays as follow:
Override protected void configure(HttpSecurity http) throws Exception {

        http = http.cors().and().csrf().disable();
        http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());

        // Set session management to stateless
        http = http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and();
        // Set unauthorized requests exception handler
        http = http
                .exceptionHandling()
                .authenticationEntryPoint(new AuthException())
                .and();
        http.addFilterBefore(requestFilter, UsernamePasswordAuthenticationFilter.class);
    }

在控制器中,映射是:

    public ResponseEntity<PaymentCard> deletePaymentCard(@PathVariable Long cardNumber) {
        PaymentCard pCard = paymentCardService.deletePaymentCard(cardNumber);
        return new ResponseEntity<>(pCard, HttpStatus.OK);
    }

我尝试了很多解决方案,比如添加@CrossOrigin 注释、创建 CorsFilter,但似乎没有任何帮助。最终,我在我的控制器中将 DeleteMapping 更改为 GetMapping 但是 我觉得 http 政策随时可以把我抓起来:( 提前感谢您的时间和帮助。

CorsConfiguration.applyPermitDefaultValues() 并不像人们假设的那样允许所有方法,而只允许以下方法:GET、HEAD、POST.

要允许 DELETE 方法,您可以使用以下代码:

http.cors().configurationSource(c -> {
    CorsConfiguration corsCfg = new CorsConfiguration();

    // All origins, or specify the origins you need
    corsCfg.addAllowedOriginPattern( "*" );

    // If you really want to allow all methods
    corsCfg.addAllowedMethod( CorsConfiguration.ALL ); 

    // If you want to allow specific methods only
    // corsCfg.addAllowedMethod( HttpMethod.GET );     
    // corsCfg.addAllowedMethod( HttpMethod.DELETE );
    // ...
});

如果我们明确配置CorsConfiguration,我建议不要使用applyPermitDefaultValues(),而是明确指定所有需要的方法。这样就不用再去记applyPermitDefaultValues()到底启用了哪些方法,这样的代码会更容易理解。

我可以有一个 class 使用以下方法实现 Filter


@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}