春天数据休息和Cors [英] Spring Data Rest and Cors

查看:313
本文介绍了春天数据休息和Cors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有Rest接口和dart fronted的Spring Boot应用程序。

I am developing a Spring Boot application with a Rest interface and a dart fronted.

XMLHttpRequest执行完全正确处理的OPTIONS请求。此后,将发出最终的GET(/ products)请求并失败:

The XMLHttpRequest does execute a OPTIONS request which is handled totally correct. After this, the final GET ("/products") request is issued and fails:

没有Access-Control-Allow-Origin所请求的资源。原因 http:// localhost:63343 因此不允许访问。

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access.

在一些调试后,我发现了以下:
AbstractHandlerMapping.corsConfiguration为所有子类填充,除了RepositoryRestHandlerMapping。在RepositoryRestHandlerMapping中,没有corsConfiguration在创建时存在/设置,因此它不会被识别为cors路径/资源。

=>没有附加CORS头

可能是问题?如何设置?

After some debugging I have found the following: The AbstractHandlerMapping.corsConfiguration is populated for all Subclasses except RepositoryRestHandlerMapping. In the RepositoryRestHandlerMapping no corsConfiguration is present / set at creation time and so it won't get recognized as cors path / resource.
=> No CORS headers attached
Could that be the problem? How can I set it?

配置类别:

@Configuration
public class RestConfiguration extends RepositoryRestMvcConfiguration {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowCredentials(false).allowedOrigins("*").allowedMethods("PUT", "POST", "GET", "OPTIONS", "DELETE").exposedHeaders("Authorization", "Content-Type");
    }

   ...
}

我甚至尝试设置每个注释的Cors:

I even tried to set the Cors per annotation:

@CrossOrigin( methods = RequestMethod.GET, allowCredentials = "false")
public interface ProductRepository extends CrudRepository<Product, String> {


}

原始请求标头:

GET /products HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
authorization: Basic dXNlcjpwYXNzd29yZA==
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/43.0.2357.130 Chrome/43.0.2357.130 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:63343/inventory-web/web/index.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

原始回应标头:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 30 Jul 2015 15:58:03 GMT

使用的版本:
Spring Boot 1.3.0.M2
Spring 4.2.0.RC2

Versions used: Spring Boot 1.3.0.M2 Spring 4.2.0.RC2

我想错过什么?

感谢,
Thomas

Thanks, Thomas

推荐答案

确实,使用Spring Data REST + Spring Framework 4.2时,只有 HandlerMapping 由Spring MVC WebMvcConfigurationSupport 创建的实例和使用 @CrossOrigin 注释的控制器CORS感知。

Indeed, when using Spring Data REST + Spring Framework 4.2, only HandlerMapping instances created by Spring MVC WebMvcConfigurationSupport and controllers annotated with @CrossOrigin will be CORS aware.

Spring Data REST仍然针对Spring Framework 4.1进行编译,并且不支持内置Spring Framework CORS实现。欢迎投票参与 DATAREST-573 相关问题。

Spring Data REST still compiles against Spring Framework 4.1, and does not support builtin Spring Framework CORS implementation. Feel free to vote for the DATAREST-573 related issue.

现在,我认为最好的解决方案是使用基于过滤器的方法。显然,您可以使用Tomcat,Jetty或这一个,但请注意,Spring Framework 4.2还提供了 CorsFilter 使用与 @CrossOrigin addCorsMappings(CorsRegistry注册表)方法相同的CORS处理逻辑。传递 UrlBasedCorsConfigurationSource c> corsFilter 构造函数参数 实例,您可以轻松获得与Spring本机CORS全局支持一样强大的功能。

Right now, I think the best solution is to use a filter based approach. You could obviously use Tomcat, Jetty or this one, but be aware that Spring Framework 4.2 also provides a CorsFilter that use the same CORS processing logic that @CrossOrigin and addCorsMappings(CorsRegistry registry) approaches. By passing an UrlBasedCorsConfigurationSource instance to the CorsFilter constructor parameter, you could easily get something as powerful as Spring native CORS global support.

如果你使用Spring Boot(支持 Filter bean),它可能是这样:

If you are using Spring Boot (which supports Filter beans), it could be something like:

@Configuration
public class RestConfiguration {

    @Bean
    public CorsFilter corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // you USUALLY want this
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

Spring Data团队目前正在寻找方法让用户定制CORS处理(即在 HandlerMapping 上调用 setCorsConfigurations(Map 配置)实例Spring Data REST部署),但我认为最好使用 CorsFilter 方法,直到 DATAREST-573 已解决。

The Spring Data team is currently looking into ways to let the user customize the CORS handling on it (i.e. calling setCorsConfigurations(Map<String, CorsConfiguration> configurations) on the HandlerMapping instance Spring Data REST deploys), but I think it is better to use the CorsFilter approach until DATAREST-573 is resolved.

Hendy的补充:在我的例子中,简单的 @Bean Filter 上面的定义不工作,我不得不使用这个:(它可以与我的使用Spring Security或 ocpsoft重写,但Sebastien在这方面更专业..我真的不知道为什么)

Hendy's addition: In my case, the simple @Bean Filter definition above does not work, I had to use this: (It may have something to do with my usage of Spring Security or ocpsoft rewrite, but Sebastien is more expert in this.. I don't really know why)

/**
 * http://stackoverflow.com/a/31748398/122441 until https://jira.spring.io/browse/DATAREST-573
 * @return
 */
@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");
    source.registerCorsConfiguration("/**", config);
    // return new CorsFilter(source);
    final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

这篇关于春天数据休息和Cors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆