原文地址:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin. For example, as you’re checking your bank account in one tab, you could have the evil.com website in another tab. The scripts from evil.com shouldn’t be able to make AJAX requests to your bank API (withdrawing money from your account!) using your credentials.

Cross-origin resource sharing (CORS) is a W3C specification implemented by most browsers that allows you to specify in a flexible way what kind of cross domain requests are authorized, instead of using some less secured and less powerful hacks like IFrame or JSONP.

Spring Framework 4.2 GA provides first class support for CORS out-of-the-box, giving you an easier and more powerful way to configure it than typical filter based solutions.

Spring MVC provides high-level configuration facilities, described bellow.

Controller method CORS configuration

You can add to your @RequestMapping annotated handler method a @CrossOrigin annotation in order to enable CORS on it (by default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation):

@RestController
@RequestMapping("/account")
public class AccountController { @CrossOrigin
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}

It is also possible to enable CORS for the whole controller:

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController { @RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}

In this example CORS support is enabled for both retrieve() and remove() handler methods, and you can also see how you can customize the CORS configuration using @CrossOrigin attributes.

You can even use both controller and method level CORS configurations, Spring will then combine both annotation attributes to create a merged CORS configuration.

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController { @CrossOrigin(origins = "http://domain2.com")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}

Global CORS configuration

In addition to fine-grained, annotation-based configuration you’ll probably want to define some global CORS configuration as well. This is similar to using filters but can be declared withing Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GETHEAD and POST methods are allowed.

JavaConfig

Enabling CORS for the whole application is as simple as:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}

You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}

XML namespace

It is also possible to configure CORS with the mvc XML namespace.

This minimal XML configuration enable CORS on /** path pattern with the same default properties than the JavaConfig one:

<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>

It is also possible to declare several CORS mappings with customized properties:

<mvc:cors>

	<mvc:mapping path="/api/**"
allowed-origins="http://domain1.com, http://domain2.com"
allowed-methods="GET, PUT"
allowed-headers="header1, header2, header3"
exposed-headers="header1, header2" allow-credentials="false"
max-age="123" /> <mvc:mapping path="/resources/**"
allowed-origins="http://domain1.com" /> </mvc:cors>

How does it work?

CORS requests (including preflight ones with an OPTIONS method) are automatically dispatched to the various HandlerMappings registered. They handle CORS preflight requests and intercept CORS simple and actual requests thanks to a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (like Access-Control-Allow-Origin). CorsConfiguration allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. It can be provided in various ways:

Spring Boot integration

CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.

Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.

Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:

@Configuration
public class MyConfiguration { @Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}

Filter based CORS support

In order to support CORS with filter-based security framework like Spring Security, or with other projects that does not support natively CORS yet like Spring Data REST, we also provide a CorsFilter. In that case, instead of using @CrossOrigin or WebMvcConfigurer#addCorsMappings(CorsRegistry), you can for example declare the filter as following in your Spring Boot application:

@Configuration
public class MyConfiguration { @Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}

CORS support in Spring Framework--官方的更多相关文章

  1. spring 官方下载地址(Spring Framework 3.2.x&Spring Framework 4.0.x)

    spring官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...

  2. Spring Framework jar官方直接下载路径

    SPRING官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...

  3. Spring 5.0.0.RC1 - CORS Support 【译文】

    3 CORS支持 3.1 介绍 出于安全考虑,浏览器禁止对当前源之外的资源进行AJAX调用.例如,当你在一个标签页检查你的银行账户时,你可以在另一个标签页打开evil.com的网站.在evil.com ...

  4. [转]spring 官方下载地址(Spring Framework 3.2.x&Spring Framework 4.0.x)

    SPRING官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...

  5. 浅谈对Spring Framework的认识

    Spring Framework,作为一个应用框架,官方的介绍如下: The Spring Framework provides a comprehensive programming and con ...

  6. Hello Spring Framework——依赖注入(DI)与控制翻转(IoC)

    又到年关了,还有几天就是春节.趁最后还有些时间,复习一下Spring的官方文档. 写在前面的话: Spring是我首次开始尝试通过官方文档来学习的框架(以前学习Struts和Hibernate都大多是 ...

  7. Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->关于spring framework中的beans

    Spring framework中的beans 1.概述 bean其实就是各个类实例化后的对象,即objects spring framework的IOC容器所管理的基本单元就是bean spring ...

  8. Spring Framework基础学习

    Spring Framework基础学习 Core support for dependency injection,transaction management,web applications,d ...

  9. Spring框架中文件目录遍历漏洞 Directory traversal in Spring framework

    官方给出的描述是Spring框架中报告了一个与静态资源处理相关的目录遍历漏洞.某些URL在使用前未正确加密,使得攻击者能够获取文件系统上的任何文件,这些文件也可用于运行SpringWeb应用程序的进程 ...

随机推荐

  1. 【Henu ACM Round#24 D】Iterated Linear Function

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 把B提取出来就是一个等比数列了. 求和一下会发现是这种形式. \(B*\frac{(A^n-1)}{A-1}+A^n*x\) 则求一 ...

  2. 2015 Multi-University Training Contest 1 hdu 5290 Bombing plan

    Bombing plan Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)To ...

  3. 10个关于Android开发的实用教程

    本文为致力于Android应用的开发人员精选了几个不错的实用教程,无论是初学者还是专业开发人员都应该能够从中获益.这些教程中有不少是关于绘图和地址服务运用的,另外一些则是SDK相关的.希望对大家有所帮 ...

  4. Mybatis Generator for SQL Server

    Mybatis Generator for SQL Server <?xml version="1.0" encoding="UTF-8" ?> & ...

  5. mysql-幻读及其例子

    第一步建表并插入5条记录:  接下来我们看下大部分mysql所说的幻读现象: 事务1(开启事务查询发现没有记录6准备插入):  事务2(开启事务,发现没有记录6插入,并提交事务):  事务1:查询发现 ...

  6. Linux线程相互排斥量--进程共享属性

    多线程中.在相互排斥量和 读写锁的 属性中.都有一个叫 进程共享属性 . 对于相互排斥量,查询和设置这个属性的方法为: pthread_mutexattr_getpshared pthread_mut ...

  7. AD域导入导出命令

    AD域 批量组织机构.用户导入导出 参考网站 https://technet.microsoft.com/zh-cn/library/cc753447(v=ws.11).aspx 导入所有命令 均cm ...

  8. vmware workstation虚拟机克隆后不能上网(桥接模式下)

    (CentOS6.8下) 重启新克隆的虚拟机,输入用户名密码,进入系统. 1.修改网卡配置,输入 vi /etc/sysconfig/network-scripts/ifcfg-eth0 出现类似如下 ...

  9. dedecms4张关键表解析之2

    4张核心表的具体情况: 1.第一张表:dede_arctype  栏目表 字段解析: topid:上一级的id(0表示为顶级,1表示为下一级....) typename: 栏目名称 typedir:栏 ...

  10. iOS ReactiveCocoa 最全常用API整理(可做为手册查询)

    本文适合有一定RAC基础的童鞋做不时的查询,所以本文不做详细解释. 一.常见类 1.RACSiganl 信号类. RACEmptySignal :空信号,用来实现 RACSignal 的 +empty ...