【问题标题】:CORS settings in Spring boot does not workSpring boot 中的 CORS 设置不起作用
【发布时间】:2019-10-25 12:30:37
【问题描述】:

我有 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

我还必须从 web 配置中删除注释 @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.

知道如何解决这个问题吗? 非常感谢。

【问题讨论】:

  • 你的CORS配置代码被调用了吗? WebMvcConfigurer@EnableWebMvc 紧密耦合。
  • 当我收到来自xxxx.yyyyy.me 的请求时,您是否在任何restapi 工具上使用任何网络浏览器?

标签: spring spring-boot cors


【解决方案1】:

我使用过如下所示的,它工作得非常好。请看我的配置文件。

WebConfig.java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

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

【讨论】:

  • 这只有在你有@EnableWebMvc 时才有效。但我不能使用那个注释
  • 您可以在主类(或)控制器中使用@CrossOrigin。
  • 我想在一个地方允许它。我不想将它添加到每个控制器中
  • 在主类中添加@CrossOrigin("*")。
【解决方案2】:
/**
 * 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;
}

【讨论】:

  • 我在哪里添加这个bean?在我的主要 java 类中?
【解决方案3】:

尝试添加

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

    }

【讨论】:

    【解决方案4】:

    尝试以下实现。它总是对我有用。将 * 对 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() {}
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2019-08-25
      • 2019-11-13
      • 2020-03-23
      相关资源
      最近更新 更多