spring Sping Boot 中的CORS设置不起作用

csbfibhn  于 2023-05-05  发布在  Spring
关注(0)|答案(7)|浏览(225)

我有Springboot(v 2.0)应用程序。我在www.example.com中启用了CORSapplication.properties,如下所示。

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

另外,在Web安全中,我添加了以下内容:

@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.

有办法解决吗?谢谢。

o7jaxewo

o7jaxewo1#

/**
 * 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;
}
ruyhziif

ruyhziif2#

我已经使用了像下面这是工作完美的罚款。请查看我的配置文件。

WebConfig.java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

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

vsdwdz233#

试试下面的实现。对我来说总是有效的。将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() {}

}
zour9fqk

zour9fqk4#

试着加上

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

    }
hi3rlvi2

hi3rlvi25#

我也有同样的问题。我不明白的是,management.endpoints.web.cors属性只是用于Spring Actuator管理端点(例如,/health)。
要实际设置常规服务端点的CORS属性,需要通过编程来设置它们,正如这里的其他答案正确显示的那样。

ct3nt3jp

ct3nt3jp6#

我们在项目中有一个有点细粒度的列表,我们使用如下配置属性配置允许的起源:

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = jHipsterProperties.getCors();
    log.debug("Registering CORS filter");
    source.registerCorsConfiguration("/actuator/**", config);
    source.registerCorsConfiguration("/oauth2/**", config);
    source.registerCorsConfiguration("/management/**", config);
    source.registerCorsConfiguration("/v3/api-docs", config);
    source.registerCorsConfiguration("/swagger-ui/**", config);
    return new CorsFilter(source);
}

注意,jHipsterProperties是一个示例,它包含了spring中定义的标准CorsConfiguration pojo。您可以在自定义配置中自由使用它,然后在配置文件中使用它,如下所示:

jhipster:
  cors:
    allowed-origins: "http://localhost:8100,http://localhost:9000"
    allowed-methods: "*"
    allowed-headers: "*"
    exposed-headers: "Authorization,Link,X-Total-Count,X-${jhipster.clientApp.name}-alert,X-${jhipster.clientApp.name}-error,X-${jhipster.clientApp.name}-params"
    allow-credentials: true
    max-age: 1800
woobm2wo

woobm2wo7#

注册您自己的CORS处理器的变体取决于控制器注册的类型:

  • 带有@Controller的默认变量将RequestMappingHandlerMapping用于寄存器CORS
  • 你使用了函数样式注册

在我看来,你可以尝试扩展AbstractUrlHandlerMapping或其他层次结构。为了找到具体的实现,您可以在函数org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#registerHandler中的debug中停留
最近我自己调查了看起来像问题,并使用了这个方法。
我的结果是:

  • 扩展类RequestMappingHandlerMapping
  • 覆盖方法initCorsConfiguration,用于生成配置路径的行为
  • 通过函数io.github.iruzhnikov.webmvc.servlet.CorsPropWebMvcRegistrations#getRequestMappingHandlerMapping注册
  • 通过函数io.github.iruzhnikov.webmvc.servlet.CorsPropWebMvcConfigurationSupport#createRequestMappingHandlerMapping注册
  • 扩展类io.github.iruzhnikov.webmvc.servlet.SpringMvcCorsConfigurer
  • 用于注册新CorsConfig的重写方法addCorsMappings
  • 典型Bean的注册ID

相关问题