SpringBoot arranged cross-domain requests Cors

I. Introduction Origin Policy

Same Origin Policy [same origin policy] is a safety feature browser client script different sources in the absence of express authorization, can not read and write other resources. Same Origin Policy is the cornerstone of browser security.

What is the source

Source [origin] is the protocol, domain name and port number. For example: http: //www.baidu.com: 80 this URL.

What is homologous

If the address inside the protocol, domain name and port number are the same it belongs to homologous.

Determine whether homologous

The following example determines URLwhether homologous http://www.a.com/test/index.html

  • http://www.a.com/dir/page.html homologous
  • http://www.child.a.com/test/index.html different sources, different domain name
  • https://www.a.com/test/index.html different sources, different protocols
  • http://www.a.com:8080/test/index.html different source port numbers are not the same

What operations are not the same origin policy restrictions

  1. Page links, and redirects form submissions are not subject to the same origin policy restrictions;
  2. The introduction of cross-domain resources is possible. But JScan not read and write content to load. The embedded into the page <script src="..."></script>, <img>, <link>, <iframe>and the like.

Cross-domain

Affected stated before the browser's same-origin policy, the script is not homologous to other sources the following objects can not operate. Want to operate another object under the cross-domain source is required. In the same-origin policy restrictions, non-homologous can not be sent between sites  AJAX request.

How to Cross-Domain

  • Domain drop

    You can set  document.damain='a.com'the browser will believe that they are the same source. Want to achieve communication between any two or more pages, two pages must be set documen.damain='a.com'.

  • JSONPCross-domain

  • CORS Cross-domain

二、CORS 简介

为了解决浏览器同源问题,W3C 提出了跨源资源共享,即 CORS(Cross-Origin Resource Sharing)。

CORS 做到了如下两点:

  • 不破坏即有规则
  • 服务器实现了 CORS 接口,就可以跨源通信

基于这两点,CORS 将请求分为两类:简单请求和非简单请求。

1、简单请求

CORS出现前,发送HTTP请求时在头信息中不能包含任何自定义字段,且 HTTP 头信息不超过以下几个字段:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type 只限于 [application/x-www-form-urlencoded 、multipart/form-datatext/plain ] 类型

一个简单的请求例子:

GET /test HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Origin: http://www.examples.com
Host: www.examples.com

对于简单请求,CORS的策略是请求时在请求头中增加一个Origin字段,服务器收到请求后,根据该字段判断是否允许该请求访问。

  1. 如果允许,则在 HTTP 头信息中添加 Access-Control-Allow-Origin 字段,并返回正确的结果 ;
  2. 如果不 允许,则不在 HTTP 头信息中添加 Access-Control-Allow-Origin 字段 。

除了上面提到的 Access-Control-Allow-Origin ,还有几个字段用于描述 CORS 返回结果 :

  1. Access-Control-Allow-Credentials: 可选,用户是否可以发送、处理 cookie
  2. Access-Control-Expose-Headers:可选,可以让用户拿到的字段。有几个字段无论设置与否都可以拿到的,包括:Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma 。

2、非简单请求

对于非简单请求的跨源请求,浏览器会在真实请求发出前,增加一次OPTION请求,称为预检请求(preflight request)。预检请求将真实请求的信息,包括请求方法、自定义头字段、源信息添加到 HTTP 头信息字段中,询问服务器是否允许这样的操作。

例如一个DELETE请求:

OPTIONS /test HTTP/1.1
Origin: http://www.examples.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: X-Custom-Header
Host: www.examples.com

与 CORS 相关的字段有:

  1. 请求使用的 HTTP 方法 Access-Control-Request-Method ;
  2. 请求中包含的自定义头字段 Access-Control-Request-Headers 。

服务器收到请求时,需要分别对 OriginAccess-Control-Request-MethodAccess-Control-Request-Headers 进行验证,验证通过后,会在返回 HTTP头信息中添加 :

Access-Control-Allow-Origin: http://www.examples.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1728000

他们的含义分别是:

  1. Access-Control-Allow-Methods: 真实请求允许的方法
  2. Access-Control-Allow-Headers: 服务器允许使用的字段
  3. Access-Control-Allow-Credentials: 是否允许用户发送、处理 cookie
  4. Access-Control-Max-Age: 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求

当预检请求通过后,浏览器会发送真实请求到服务器。这就实现了跨源请求。

三、Spring Boot 配置 CORS

1、使用@CrossOrigin 注解实现

#如果想要对某一接口配置 CORS,可以在方法上添加 @CrossOrigin 注解 :

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
    return "{\"project\":\"just a test\"}";
}

#如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效:

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
    
}

#如果想添加全局配置,则需要添加一个配置类 :

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

另外,还可以通过添加 Filter 的方式,配置 CORS 规则,并手动指定对哪些接口有效。

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);   config.addAllowedOrigin("http://localhost:9000");
    config.addAllowedOrigin("null");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
    FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

基于XML配置

<mvc:cors>
    <mvc:mapping path="/api/*" 
        allow-credentials="true"
        allowed-headers=""
        allowed-methods=""
        allowed-origins=""
        exposed-headers=""
        max-age="123"/>
</mvc:cors>

默认情况下,@CrossOrigin允许所有的来源,所有的Header,@RequestMapping注解中指定的HTTP方法被跨域访问,并支持最大30分钟的maxAge。 您可以覆盖这些注解属性值,以进行个性化设置:

属性 说明
origins 允许的来源列表。响应信息会放在HTTP协议Header的Access-Control-Allow-Origin中
-*- 所有的来源都被允许
--- 如果未定义,则允许所有来源)
allowedHeaders 实际请求期间可以使用的请求头列表。该值用于预检的响应Header中的Access-Control-Allow-Headers信息。
-*- 意味着允许客户端请求的所有头信息。
--- 如果未定义,则允许所有请求的headers。
methods 服务器端支持的HTTP请求方法列表。
-*- 所有方法。
--- 如果未定义,则使用由RequestMapping注解定义的方法。
exposedHeaders 浏览器允许客户端访问的响应头列表。 在实际响应报头Access-Control-Expose-Headers中设置值。
–-- 如果未定义,则使用空的暴露标题列表。
allowCredentials 它确定浏览器是否应该包含与请求相关的任何cookie。
-false- 不允许包含Cookies 。
–true– 允许携带Cookies。
–""- (空字符串) 意味着未定义。
–-- 如果未定义,则允许所有凭据。
maxAge 预响应缓存持续时间的最大时间(以秒为单位)。 该值在Header的Access-Control-Max-Age中设置。
–-- 如果未定义, 最大时间设置为1800秒(30分钟)

Guess you like

Origin www.cnblogs.com/deityjian/p/11515275.html