Spring Global CORS configuration not working but Controller level config does

后端 未结 10 1109
臣服心动
臣服心动 2020-12-14 06:25

I am trying to configure CORS globally via WebMvcConfigurerAdapter shown below. To test I am hitting my API endpoint via a small node app I created to emulate a

10条回答
  •  臣服心动
    2020-12-14 07:01

    I've just been having the exact same issue, with none of the solutions in this thread working. I've managed to solve it with the following:

    A new configuration bean:

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class CorsFilterConfiguration {
    
      @Bean
      public CorsFilter corsFilter() {
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          CorsConfiguration config = new CorsConfiguration();
          config.setAllowCredentials(true);
          config.addAllowedOrigin("*");
          config.setAllowedMethods(Arrays.asList("POST", "OPTIONS", "GET", "DELETE", "PUT"));
          config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
          source.registerCorsConfiguration("/**", config);
          return new CorsFilter(source);
      }
    }
    

    A modification to my web.xml to add a new filter for all URLs:

    
      corsFilter
      org.springframework.web.filter.DelegatingFilterProxy
    
    
      corsFilter
      /*
    
    

    Obviously you can modify the cors config accordingly.

提交回复
热议问题