春季靴子CORS块删除请求

发布于 2025-02-02 12:23:22 字数 1919 浏览 2 评论 0原文

Whenever I try to send request to delete endpoint with axios, I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/api/payment_card/delete/1234123412343433' from 原始'http:// localhost:3000'被CORS策略阻止:响应前飞行请求 不通过访问控制检查:没有“访问控制”标头 请求的资源

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,但似乎没有任何帮助。最终,我更改了删除以在控制器中获取映射,但是 我觉得HTTP政策可以随时吸引我拘留:( 感谢您的时间并提前帮助。

Whenever I try to send request to delete endpoint with axios, I get the following error:

Access to XMLHttpRequest at 'http://localhost:8080/api/payment_card/delete/1234123412343433' from
origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the
requested resource

Axios request is built as following :

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

And in the controller, mapping is :

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

I tried many solutions like adding @CrossOrigin annotation, making CorsFilter but nothing seems to help at all. Ultimately, I've changed DeleteMapping to GetMapping in my controller but
I feel like http policy can catch me to custody at any time :(
Thanks for your time and help in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏了南城 2025-02-09 12:23:22

corsconfiguration.applypermitdefaultValues()允许不像人们那样假设的所有方法,而只允许使用:遵循方法:get,head,post。

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

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() 的准确启用哪些方法,并且此类代码将更易于理解。

CorsConfiguration.applyPermitDefaultValues() allows not all methods as one may assume, but following methods only: GET, HEAD, POST.

To allow DELETE method, you can use following code:

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 );
    // ...
});

If we configure CorsConfiguration explicitly, I recommend not to use applyPermitDefaultValues(), but specify all desired methods explicitly. Then nobody will need to remember what methods exactly are enabled by applyPermitDefaultValues(), and such code will be easier to understand.

番薯 2025-02-09 12:23:22

我可以使用以下方法实现过滤器的类


@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 {
    }
}


I could have a class that implements Filter with the following methods


@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 {
    }
}


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文