Spring Boot中的CORS设置不起作用

时间:2019-06-11 06:25:14

标签: spring spring-boot cors

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

有人知道如何解决此问题吗? 非常感谢。

4 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

我用过下面的方法,效果很好。请参阅我的配置文件。

WebConfig.java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

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

答案 2 :(得分:0)

只需尝试添加

公共类CorsFilter实现了过滤器{

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

}

答案 3 :(得分:0)

尝试以下实施。它总是对我有用。用您的特定来源将*替换为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() {}

}