簡體   English   中英

Spring Boot CORS 阻止 DELETE 請求

[英]Spring Boot CORS blocks DELETE requests

每當我嘗試使用 axios 發送刪除端點的請求時,都會收到以下錯誤:

從源“http://localhost:3000”訪問“http://localhost:8080/api/payment_card/delete/1234123412343433”處的 XMLHttpRequest 已被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭

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()究竟啟用了哪些方法,這樣的代碼將更容易理解。

我可以有一個使用以下方法實現過濾器的類


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


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM