26. CORS Support
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 open in another tab. The scripts from evil.com should not be able to make AJAX requests to your bank API (e.g., 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.
As of Spring Framework 4.2, CORS is supported out of the box. CORS requests (including preflight ones with an OPTIONS
method) are automatically dispatched to the various registered HandlerMappings. 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
) based on the CORS configuration you have provided.
Since CORS requests are automatically dispatched, you do not need to change the |
You can add an @CrossOrigin
annotation to your @RequestMapping
annotated handler method 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, path = "/{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, path = "/{id}") public void remove(@PathVariable Long id) { // ... } }
In the above example CORS support is enabled for both the retrieve()
and the remove()
handler methods, and you can also see how you can customize the CORS configuration using @CrossOrigin
attributes.
You can even use both controller-level and method-level CORS configurations; Spring will then combine attributes from both annotations to create merged CORS configuration.
@CrossOrigin(maxAge = 3600) @RestController @RequestMapping("/account") public class AccountController { @CrossOrigin("http://domain2.com") @RequestMapping("/{id}") public Account retrieve(@PathVariable Long id) { // ... } @RequestMapping(method = RequestMethod.DELETE, path = "/{id}") public void remove(@PathVariable Long id) { // ... } }
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 within Spring MVC and combined with fine-grained @CrossOrigin
configuration. By default all origins and GET
, HEAD
, and POST
methods are allowed.
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); } }
The following minimal XML configuration enables CORS for the /**
path pattern with the same default properties as with the aforementioned JavaConfig examples:
<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>
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 aMap
with several CorsConfiguration instances mapped to path patterns like/api/**
. - Subclasses can provide their own
CorsConfiguration
by overriding theAbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest)
method. - Handlers can implement the
CorsConfigurationSource
interface (likeResourceHttpRequestHandler
now does) in order to provide a CorsConfigurationinstance for each request.
相关推荐
下面小编就为大家分享一篇spring4.3 实现跨域CORS的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
基于CORS的geoserver跨域访问,具体配置可参考博文http://blog.csdn.net/longshengguoji/article/details/46625489
spring解决跨域问题(两种方式,配有文档) cors-filter-1.7.jar java-property-utils-1.9.1.jar
跨域插件,备用下,好不容易找到,有个太贵了,一个积分意思意思,H5开发必备的chrome插件
通过设置访问代理,解决vue axios 跨域访问问题
跨域资源共享CORS协议介绍, cross-origin resource sharing layer
cors跨域
cors跨域需要的cors-filter-1.7.1.jar和java-property-utils-1.9.1.jar,一个拦截器配置文件
亲测可用,cors-filter-1.7,java-property-utils-1.9下载
本篇文章主要介绍了Spring boot 总结之跨域处理cors的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1 说明: Cors(跨域)限制中间件可以解决一些Cors(跨域)异常例如:...4、 如果前端项目是App应用程序,则必须在后端项目中定义Cors(跨域)限制中间件,且IP域名端口必须是:http://127.0.0.1:8080,而不能是:http://loc
本篇文章主要介绍了详解Spring MVC CORS 跨域 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
主要介绍了Spring Boot 通过CORS实现跨域,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
SpringMVC CORS跨域测试包
当使用ajax跨域请求时,浏览器报错:XmlHttpRequest error...使用CORS,可以使用普通的ajax实现跨域,这对于前端来说是极大的福音了,这个技术被现在大多数浏览器所普遍支持,因为跨域已经是普遍的要求,浏览器肯定会逐渐
解决tomcat跨域所需的两个jar包cors-fiter.jar&java;-property.jar
cors跨域Tomcat http://blog.csdn.net/itas109/article/details/70285802
php版跨域 ajax+jsonp例子源代码.zip
最全面关于J2EE跨域资源共享的解决方案以及所需要依赖的Jar包,cors-filter-1.7.jar,java-property-utils-1.9.jar,绝对能用
Spring,跨域 ,解决方案,官方, demo,cros