【Spring】Spring Framework Reference Documentation中文版24

来源:互联网 发布:linux ftp命令 带端口 编辑:程序博客网 时间:2024/09/21 08:15

27. CORS Support

CORS支持

 

27.1 Introduction

介绍

 

For security reasons, browsers prohibit AJAX calls to resources residing outside the current origin. For example, as youre 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.

出于安全的原因,浏览器阻止AJAX调用资源来读取当前区域外部的资源。例如你查看你的银行卡余额在一个页面标签中,你有一个evil.com的网站打开在另一个页面。evil.com中脚本应该不能使用AJAX请求来访问你的银行API(例如转移你账户中的余额)在使用你的授权下。

 

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.

跨域资源共享(CORS)是W3C指定实现通过大多数浏览器允许你来指定合适的方式有关授权的跨域请求,来代替一些不安全和无伤害的例如IFRAMEJSONP

 

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.

由于spring框架4.2,CORS是支持的。CORS请求(包括使用OPTIONS方法的)是自动转发不同的注册HandlerMappings。他们处理CORS请求和打断CORS请求由于CorsProcessor的实现(默认是DefaultCorsProcessor)用于添加相关的CORS响应头(例如Access-Control-Allow-Origin)基于你提供的CORS配置。

 

[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.

因此CORS请求被自动转发,你不需要改变DispatcherServletdispatchOptionsRequest初始化参数值,使用默认值(false)是推荐的方式。

 

27.2 Controller method CORS configuration

控制器方法的CORS配置

 

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:

你可以添加一个@CrossOrigin注解到你的@RequestMapping注解修饰的处理器方法用于启用CORS。默认的@CrossOrigin允许所有的originHTTP方法指定在@RequestMapping注解中:

 

@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:

也可以对整个控制器启用CORS

 

@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.

在上面的例子中CORS支持retrieveremove的处理方法,并且你可以知道你能自定义CORS配置通过使用@CrossOrigin属性。

 

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.

你甚至可以使用控制器级别和方法级别的CORS配置;spring将组合他们的属性来自注解并且创建合并的CORS配置。

 

@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) {

// ...

}

}

 

27.3 Global CORS configuration

全局的CORS配置

 

In addition to fine-grained, annotation-based configuration youll 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.

此外对于细粒度的控制、基于注解的配置你也可以定义一些全局的CORS配置。这和使用过滤器很相似但是可以定义在springmvc中并且组合细粒度的@CrossOrigin配置。默认的所有的originGETHEADPOST方法是被允许的。

 

27.3.1 JavaConfig

 

Enabling CORS for the whole application is as simple as:

开启CORS对于整个应用也可以设置如下:

 

@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:

你可以简单的改变任何属性,并且应用CORS配置对于特定的路径模式:

 

@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);

}

}

 

27.3.2 XML namespace

xml命名空间

 

The following minimal XML configuration enables CORS for the /** path pattern with the same default properties as with the aforementioned JavaConfig examples:

下面是xml的配置来开启CORS用于/**的路径模式对于相同的默认属性类似于上面提到的Java配置的例子:

 

<mvc:cors>

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

</mvc:cors>

 

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

也可以定义一些CORS匹配自定义的属性:

 

<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>

 

27.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:

CorsConfiguration允许你指定CORS请求如何被处理:允许originheader、方法等等。他可以被提供通过多种方式:

 

    AbstractHandlerMapping#setCorsConfiguration() allows to specify a Map with several CorsConfiguration instances mapped to path patterns like /api/**.

 AbstractHandlerMapping#setCorsConfiguration允许指定一个Map有一些CorsConfiguration的实例匹配路径类似于/api/**

    Subclasses can provide their own CorsConfiguration by overriding the AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest) method.

子类可以提供他们自己的CorsConfiguration通过覆盖AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest)方法

    Handlers can implement the CorsConfigurationSource interface (like ResourceHttpRequestHandler now does) in order to provide a CorsConfiguration instance for each request.

处理器可以实现CorsConfigurationSource接口(就像ResourceHttpRequestHandler现在实现的)用于提供一个CorsConfiguration实例对于每个请求。

 

27.5 Filter based CORS support

基于CORS支持的过滤器

 

In order to support CORS with filter-based security frameworks like Spring Security, or with other libraries that do not support natively CORS, Spring Framework also provides a CorsFilter. Instead of using @CrossOrigin or WebMvcConfigurer#addCorsMappings(CorsRegistry), you need to register a custom filter defined like bellow:

为了支持CORS基于过滤器的安全框架例如springSecurity,或其他库不支持CORSspring框架也提供了一个CorsFilter。用于代替使用@CrossOriginWebMvcConfigurer#addCorsMappings(CorsRegistry),你需要注册一个自定义的过滤器定义如下:

 

import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import org.springframework.web.filter.CorsFilter;

 

public class MyCorsFilter extends CorsFilter {

 

public MyCorsFilter() {

super(configurationSource());

}

 

private static UrlBasedCorsConfigurationSource configurationSource() {

CorsConfiguration config = new CorsConfiguration();

config.setAllowCredentials(true);

config.addAllowedOrigin("http://domain1.com");

config.addAllowedHeader("*");

config.addAllowedMethod("*");

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

source.registerCorsConfiguration("/**", config);

return source;

}

}

 

You need to ensure that CorsFilter is ordered before the other filters, see this blog post about how to configure Spring Boot accordingly.

你需要保证CorsFilter在其他过滤器之前,见这个博客有关如何配置springboot

 

 

阅读全文
0 0
原创粉丝点击