`

spring4 跨域支持CORS Support

 
阅读更多

26. CORS Support

26.1 Introduction

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.

[Note]

Since CORS requests are automatically dispatched, you do not need to change the DispatcherServlet dispatchOptionsRequest init parameter value; using its default value (false) is the recommended approach.

26.2 Controller method CORS configuration

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) {
		// ...
	}
}

26.3 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 within Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GETHEAD, and POST methods are allowed.

26.3.1 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);
	}
}

26.3.2 XML namespace

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>

 

26.4 Advanced Customization

CorsConfiguration allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. It can be provided in various ways:

分享到:
评论

相关推荐

    cesium跨域加载问题

    此外,如果你使用的是Spring Boot或其他基于Java的Web框架,可能需要在配置类中添加对应的跨域配置,而不是修改`web.xml`。 在Cesium客户端代码中,确保你的请求正确处理了跨域问题,例如设置`withCredentials`为`...

    tomcat跨域访问问题

    4. **使用Tomcat的CORS Valve**:Tomcat 7.0.53及以上版本提供了CORS Valve,可以在server.xml的Host或Context元素中配置: ```xml allowCredentials="true" allowedHeaders="*" allowedMethods="*" ...

    配置服务端支持跨域所应用到的jar包

    &lt;param-name&gt;cors.support.credentials &lt;param-value&gt;true &lt;param-name&gt;cors.max.age &lt;param-value&gt;3600 &lt;filter-name&gt;CorsFilter &lt;url-pattern&gt;/* ``` 在实际开发中,我们不建议将`allowedOrigins...

    Spring MVC中自带的跨域问题解决方法

    1. [CORS Support in the Spring Framework](https://spring.io/blog/2015/06/08/cors-support-in-spring-framework) 希望本文的内容能帮助到你理解和解决在Spring MVC中遇到的跨域问题,如果还有其他疑问,欢迎...

    geoserver跨域jar包

    &lt;param-name&gt;cors.support.credentials &lt;param-value&gt;true &lt;param-name&gt;cors.max.age &lt;param-value&gt;3600 &lt;filter-name&gt;CorsFilter &lt;url-pattern&gt;/* ``` 2. 配置Geoserver:如果不想修改Web容器配置...

    tomca设置跨域.rar

    4. **Tomcat服务器配置**: 在Tomcat的conf/server.xml文件中,可以配置`&lt;Connector&gt;`元素来启用跨域支持,但这种方法通常不推荐,因为它会影响所有应用程序。 **四、注意事项** - 跨域配置的安全性:允许所有来源...

    vue+springboot前后端分离实现单点登录跨域问题解决方法

    为了解决跨域问题,我们可以使用CORS(Cross-Origin Resource Sharing)机制。 CORS配置 在SpringBoot中,我们可以使用`@Configuration`注解来配置CORS。在上面的代码中,我们使用`CorsConfiguration`类来配置CORS...

    tomcat解决跨越问题

    这段配置允许了所有源(`*`)进行GET、POST、HEAD、OPTIONS、PUT、DELETE操作,并且支持携带认证信息(`cors.support.credentials=true`)。 3. 使用Spring Boot集成CORS: 如果你的应用基于Spring Boot,可以在...

    geoserver跨域解决方案以及相关jar包整理

    总结来说,解决Geoserver的跨域问题需要开启CORS支持,并正确配置相关参数。同时,`corsjar`中的jar包是实现这一功能的关键,它们应被适当地整合到Geoserver的类路径中。理解并掌握这些步骤,将有助于构建更加灵活和...

    【开发技巧/经验分享】在Zuul网关服务中实现限流、用户鉴权(访问鉴权) 、跨域访问

    import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER; @Component public class RateLimiterFilter extends ZuulFilter { // 限流桶实现,每...

Global site tag (gtag.js) - Google Analytics