簡體   English   中英

Spring boot 中的 CORS 設置不起作用

[英]CORS settings in Spring boot does not work

我有 Springboot (v 2.0) 應用程序。 我在 application.properties 中啟用了 CORS,如下所示。

management.endpoints.web.cors.allowed-origins=http://xxxx.yyyyy.me
management.endpoints.web.cors.allowed-methods=GET,POST
management.endpoints.web.cors.allowed-headers=Authorization,Cache-Control,Content-Type,Accept,X-Requested-With,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Origin
management.endpoints.web.cors.exposed-headers=Access-Control-Expose-Headers,Authorization,Cache-Control,Content-Type,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Origin

我也不得不從網絡配置中刪除注釋 @EnableWebMvc 因為我不想使用 Thymleaf 模板(所以我使用我自己的添加視圖控制器,如下所示。)

  @Override
  public void addViewControllers(ViewControllerRegistry registry)
  {
    registry.addViewController("/").setViewName("forward:/index.html");
    registry.addViewController("/myProfile").setViewName("forward:/index.html");
  }

我還在主 java 類中添加了 CORS 配置 bean,如下所示。

public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://xxxx.yyyyy.me")
        .allowedHeaders("Authorization","Cache-Control","Content-Type","Accept","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Headers","Origin")
          .exposedHeaders("Access-Control-Expose-Headers","Authorization","Cache-Control","Content-Type","Access-Control-Allow-Origin","Access-Control-Allow-Headers","Origin");
      }
    };
  }

同樣在網絡安全中,我添加了以下內容:

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

但仍然沒有運氣。 當我收到來自http://xxxx.yyyyy.me的請求時,我收到如下所示的 CORS 錯誤。

Access to XMLHttpRequest at 'https://abcde.com/api/traveller/findTravellers?fromDate=&toDate=&gender=&orderBy=&minAge=&maxAge=&keyword=&languages=&placeObj=&needAccommodation=false&haveAccommodation=false&needCar=false&haveCar=false&lookingFriends=false&withPhotoOnly=false&page=0&totalVisible=7&size=20&totalCount=0' from origin 'http://xxxx.yyyyy.me' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

知道如何解決這個問題嗎? 多謝。

/**
 * CorsConfiguration Bean Configuration.
 * 
 * @return corsConfigurationSource.
 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("*"));
    configuration.setAllowedMethods(ImmutableList.of(HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(), HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the
    // request's credentials mode is 'include'.
    configuration.setAllowCredentials(false);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(ImmutableList.of(HttpHeaders.AUTHORIZATION, HttpHeaders.CACHE_CONTROL, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT, ORGA_ID));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

我已經使用了像下面這樣工作得很好。 請看我的配置文件。

WebConfig.java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*");
    }
}

只是嘗試添加

public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        chain.doFilter(req, res);

    }

試試下面的實現。 它總是對我有用。 將 * 對 Access-Control-Allow-Origin 替換為您的特定來源。

public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

我遇到了同樣的問題。 我無法理解的是management.endpoints.web.cors屬性僅用於 Spring Actuator 管理端點(例如/health )。

要實際設置常規服務端點的 CORS 屬性,需要以編程方式設置它們,正如此處的其他答案正確顯示的那樣。

注冊您自己的 CORS 處理器的變體取決於控制器注冊的類型:

  • @Controller的默認變體使用RequestMappingHandlerMapping來注冊 CORS
  • 您使用了函數樣式注冊

我認為,您可以嘗試從層次結構中擴展AbstractUrlHandlerMapping或其他。 為了找到具體的實現,您可以在函數org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#registerHandler中進行調試


最近我自我調查看起來像問題並使用了這種方法。
我的結果:

  • 擴展類RequestMappingHandlerMapping
    • 重寫方法initCorsConfiguration用於配置路徑的行為
    • 通過函數io.github.iruzhnikov.webmvc.servlet.CorsPropWebMvcRegistrations#getRequestMappingHandlerMapping注冊它
    • 通過函數io.github.iruzhnikov.webmvc.servlet.CorsPropWebMvcConfigurationSupport#createRequestMappingHandlerMapping注冊它
  • 擴展類io.github.iruzhnikov.webmvc.servlet.SpringMvcCorsConfigurer
    • 用於注冊新 CorsConfig 的重寫方法addCorsMappings
    • 注冊 id 像典型的 Bean

暫無
暫無

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

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