CORS support in Spring Framework--官方
原文地址: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 GET, HEAD 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:
AbstractHandlerMapping#setCorsConfiguration()allows to specify aMapwith several CorsConfiguration mapped on path patterns like/api/**- Subclasses can provide their own
CorsConfigurationby overridingAbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest)method - Handlers can implement
CorsConfigurationSourceinterface (likeResourceHttpRequestHandlernow does) in order to provide a CorsConfiguration for each request.
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--官方的更多相关文章
- spring 官方下载地址(Spring Framework 3.2.x&Spring Framework 4.0.x)
spring官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...
- Spring Framework jar官方直接下载路径
SPRING官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...
- Spring 5.0.0.RC1 - CORS Support 【译文】
3 CORS支持 3.1 介绍 出于安全考虑,浏览器禁止对当前源之外的资源进行AJAX调用.例如,当你在一个标签页检查你的银行账户时,你可以在另一个标签页打开evil.com的网站.在evil.com ...
- [转]spring 官方下载地址(Spring Framework 3.2.x&Spring Framework 4.0.x)
SPRING官方网站改版后,建议都是通过 Maven和Gradle下载,对不使用Maven和Gradle开发项目的,下载就非常麻烦,下给出Spring Framework jar官方直接下载路径: h ...
- 浅谈对Spring Framework的认识
Spring Framework,作为一个应用框架,官方的介绍如下: The Spring Framework provides a comprehensive programming and con ...
- Hello Spring Framework——依赖注入(DI)与控制翻转(IoC)
又到年关了,还有几天就是春节.趁最后还有些时间,复习一下Spring的官方文档. 写在前面的话: Spring是我首次开始尝试通过官方文档来学习的框架(以前学习Struts和Hibernate都大多是 ...
- Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->关于spring framework中的beans
Spring framework中的beans 1.概述 bean其实就是各个类实例化后的对象,即objects spring framework的IOC容器所管理的基本单元就是bean spring ...
- Spring Framework基础学习
Spring Framework基础学习 Core support for dependency injection,transaction management,web applications,d ...
- Spring框架中文件目录遍历漏洞 Directory traversal in Spring framework
官方给出的描述是Spring框架中报告了一个与静态资源处理相关的目录遍历漏洞.某些URL在使用前未正确加密,使得攻击者能够获取文件系统上的任何文件,这些文件也可用于运行SpringWeb应用程序的进程 ...
随机推荐
- redhat 7 cenos 7 网络配置文件
Cenos 7 TYPE=Ethernet PROXY_METHOD=none BROWSER_ONLY=no DEFROUTE=yes IPV4_FAILURE_FATAL=no NAME=eth0 ...
- HNU 13108 Just Another Knapsack Problem DP + Trie树优化
题意: 给你一个文本串,和一些模式串,每个模式串都有一个价值,让你选一些模式串来组成文本串,使获得的价值最大.每个模式串不止能用一次. 思路: 多重背包,枚举文本串的每个位置和模式串,把该模式串拼接在 ...
- 【Henu ACM Round#24 E】Connected Components
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 要求把连续的一段li..ri的边全都删掉. 然后求剩下的图的联通数 如果暴力的话 复杂度显然是O(k*m)级别的. 考虑我们把li. ...
- Android中设置半个屏幕大小且居中的button布局 (layout_weight属性)
先看例如以下布局 :
- java线程共享受限资源 解决资源竞争 thinking in java4 21.3
java线程共享受限资源 解决资源竞争 具体介绍请參阅:thinking in java4 21.3 thinking in java 4免费下载:http://download.csdn.net/ ...
- java生成MD5校验码
在Java中,java.security.MessageDigest (rt.jar中)已经定义了 MD5 的计算,所以我们只需要简单地调用即可得到 MD5 的128 位整数.然后将此 128 位计 ...
- 6.C语言文件操作之英语电子字典的实现,dos版
多的不说,直接上代码: 里面涉及的字典文件在这:这是传送门,下载下来以后把该文件放在工程目录下即可 #define _CRT_SECURE_NO_WARNINGS #include <stdio ...
- Kali linux 2016.2(Rolling)中metasploit的搜集特定地址的邮件地址
不多说,直接上干货! 使用search_email_collector搜集特定地址的邮件地址 search_email_collector 要求提供一个邮箱后缀,通过多个搜索引擎的查询结果分析使用此后 ...
- Hadoop框架基础(一)
** Hadoop框架基础(一) 学习一个新的东西,传统而言呢,总喜欢漫无目的的扯来扯去,比如扯扯发展史,扯扯作者是谁,而我认为这些东西对于刚开始接触,并以开发为目的学者是没有什么帮助的,反而 ...
- 增强for循环的使用详解及代码
首先说一下他的语法结构: for(数据类型 变量 :集合){ //这里写要遍历的元素,或者所需要的代码即可//如果集合中存放的是对象,可以获取到每个对象(数据类型=对象类型 变量(遍历出来的每个对象) ...