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.
相关推荐
此外,如果你使用的是Spring Boot或其他基于Java的Web框架,可能需要在配置类中添加对应的跨域配置,而不是修改`web.xml`。 在Cesium客户端代码中,确保你的请求正确处理了跨域问题,例如设置`withCredentials`为`...
4. **使用Tomcat的CORS Valve**:Tomcat 7.0.53及以上版本提供了CORS Valve,可以在server.xml的Host或Context元素中配置: ```xml allowCredentials="true" allowedHeaders="*" allowedMethods="*" ...
<param-name>cors.support.credentials <param-value>true <param-name>cors.max.age <param-value>3600 <filter-name>CorsFilter <url-pattern>/* ``` 在实际开发中,我们不建议将`allowedOrigins...
1. [CORS Support in the Spring Framework](https://spring.io/blog/2015/06/08/cors-support-in-spring-framework) 希望本文的内容能帮助到你理解和解决在Spring MVC中遇到的跨域问题,如果还有其他疑问,欢迎...
<param-name>cors.support.credentials <param-value>true <param-name>cors.max.age <param-value>3600 <filter-name>CorsFilter <url-pattern>/* ``` 2. 配置Geoserver:如果不想修改Web容器配置...
4. **Tomcat服务器配置**: 在Tomcat的conf/server.xml文件中,可以配置`<Connector>`元素来启用跨域支持,但这种方法通常不推荐,因为它会影响所有应用程序。 **四、注意事项** - 跨域配置的安全性:允许所有来源...
为了解决跨域问题,我们可以使用CORS(Cross-Origin Resource Sharing)机制。 CORS配置 在SpringBoot中,我们可以使用`@Configuration`注解来配置CORS。在上面的代码中,我们使用`CorsConfiguration`类来配置CORS...
这段配置允许了所有源(`*`)进行GET、POST、HEAD、OPTIONS、PUT、DELETE操作,并且支持携带认证信息(`cors.support.credentials=true`)。 3. 使用Spring Boot集成CORS: 如果你的应用基于Spring Boot,可以在...
总结来说,解决Geoserver的跨域问题需要开启CORS支持,并正确配置相关参数。同时,`corsjar`中的jar包是实现这一功能的关键,它们应被适当地整合到Geoserver的类路径中。理解并掌握这些步骤,将有助于构建更加灵活和...
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER; @Component public class RateLimiterFilter extends ZuulFilter { // 限流桶实现,每...