跨域访问方法介绍(7)--使用 CORS

CORS 是一个 W3C 标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 AJAX 只能同源使用的限制。本文主要介绍 CORS 的基本使用,文中所使用到的软件版本:Chrome 90.0.4430.212、jquery 1.12.4,Spring Boot 2.4.4、jdk1.8.0_181。

1、CORS 简介

CORS 需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于 IE10。整个 CORS 通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS 通信与同源的 AJAX 通信没有差别,代码完全一样。浏览器一旦发现 AJAX 请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现 CORS 通信的关键是服务器。只要服务器实现了 CORS 接口,就可以跨源通信。

1.1、两种请求

浏览器将 CORS 请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。只要同时满足以下两大条件,就属于简单请求。

(1)请求方法是以下三种方法之一:
 HEAD
 GET
 POST
(2)HTTP的头信息不超出以下几种字段:
 Accept
 Accept-Language
 Content-Language
 Last-Event-ID
 Content-Type:只限于三个值 application/x-www-form-urlencoded、multipart/form-data、text/plain

这是为了兼容表单(form),因为历史上表单一直可以发出跨域请求。AJAX 的跨域设计就是,只要表单可以发,AJAX 就可以直接发。凡是不同时满足上面两个条件,就属于非简单请求。浏览器对这两种请求的处理,是不一样的。

1.2、简单请求

1.2.1、基本流程

对于简单请求,浏览器直接发出 CORS 请求。浏览器发现跨源 AJAX 请求是简单请求,就自动在头信息之中,添加一个 Origin 字段。

Host: localhost:8081
Origin: http://localhost:8080
Pragma: no-cache
User-Agent: Mozilla/5.0  ...
Connection: keep-alive

上面的头信息中,Origin 字段用来说明本次请求来自哪个源(协议 + 域名 + 端口)。服务器根据这个值,决定是否同意这次请求。如果 Origin 指定的源,不在许可范围内,服务器会返回一个正常的HTTP 响应。浏览器发现,这个响应的头信息没有包含 Access-Control-Allow-Origin 字段,就知道出错了,从而抛出一个错误,被 XMLHttpRequest 的 onerror 回调函数捕获。注意,这种错误无法通过状态码识别,因为 HTTP 响应的状态码有可能是 200。如果 Origin 指定的域名在许可范围内,服务器返回的响应,会多出几个头信息字段。

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Expose-Headers: my-response-header
Connection: keep-alive
Content-Length: 12
Content-Type: text/plain;charset=UTF-8

上面的头信息之中,有三个与 CORS 请求相关的字段,都以 Access-Control- 开头。

(1) Access-Control-Allow-Origin
该字段是必须的。它的值要么是请求时 Origin 字段的值,要么是一个 *,表示接受任意域名的请求。
(2) Access-Control-Allow-Credentials
该字段可选。它的值是一个布尔值,表示是否允许发送 Cookie。默认情况下,Cookie 不包括在 CORS 请求之中。设为 true,即表示服务器明确许可,Cookie 可以包含在请求中一起发给服务器。这个值也只能设为 true,如果服务器不要浏览器发送 Cookie,删除该字段即可。
(3) Access-Control-Expose-Headers
该字段可选。CORS 请求时,XMLHttpRequest 对象的 getResponseHeader() 方法只能拿到6个基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必须在 Access-Control-Expose-Headers 里面指定。上面的例子指定,getResponseHeader('myResponseHeader') 可以返回 myResponseHeader 字段的值。

1.2.2、withCredentials 属性

CORS 请求默认不发送 Cookie 和HTTP认证信息。如果要把 Cookie 发到服务器,一方面要服务器同意,指定 Access-Control-Allow-Credentials字段。

Access-Control-Allow-Credentials: true

另一方面,必须在 AJAX 请求中打开 withCredentials 属性。

let xhr = new XMLHttpRequest();
xhr.withCredentials = true

否则,即使服务器同意发送 Cookie,浏览器也不会发送。或者,服务器要求设置 Cookie,浏览器也不会处理。如果省略 withCredentials 设置,有的浏览器还是会一起发送 Cookie;可以显式关闭withCredentials。

xhr.withCredentials = false;

 需要注意的是,如果要发送 Cookie,Access-Control-Allow-Origin 就不能设为星号,必须指定明确的、与请求网页一致的域名。同时,Cookie 依然遵循同源政策,只有用服务器域名设置的 Cookie 才会上传,其他域名的 Cookie 并不会上传,且(跨源)原网页代码中的 document.cookie 也无法读取服务器域名下的 Cookie。

1.3、非简单请求

1.3.1、预检请求

非简单请求是那种对服务器有特殊要求的请求,比如请求方法是 PUT 或 DELETE,或者 Content-Type 字段的类型是 application/json。非简单请求的 CORS 请求,会在正式通信之前,增加一次 HTTP 查询请求,称为"预检"请求(preflight)。浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些 HTTP 动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的 XMLHttpRequest 请求,否则就报错。

下面是预检请求的头信息:

Access-Control-Request-Headers: my-request-header
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:8080

除了 Origin 字段,预检请求的头信息包括两个特殊字段。
(1)Access-Control-Request-Method
该字段是必须的,用来列出浏览器的 CORS 请求会用到哪些HTTP方法,上例是 POST。
(2)Access-Control-Request-Headers
该字段是一个逗号分隔的字符串,指定浏览器 CORS 请求会额外发送的头信息字段,上例是 my-request-header

1.3.2、预检请求的响应

服务器收到预检请求以后,检查了 Origin、Access-Control-Request-Method 和 Access-Control-Request-Headers 字段以后,确认允许跨源请求,就可以做出回应。

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: my-request-header
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Expose-Headers: my-response-header
Access-Control-Max-Age: 1800
Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH
Connection: keep-alive
Content-Length: 0
Date: Fri, 04 Jun 2021 02:55:51 GMT
Keep-Alive: timeout=60

上面的 HTTP 回应中,关键的是 Access-Control-Allow-Origin 字段,表示 http://localhost:8080 可以请求数据。该字段也可以设为星号,表示同意任意跨源请求。

如果服务器否定了预检请求,会返回一个正常的 HTTP 回应,但是没有任何 CORS 相关的头信息字段。这时,浏览器就会认定,服务器不同意预检请求,因此触发一个错误,被 XMLHttpRequest 对象的 onerror 回调函数捕获。

预检请求响应其他 CORS 相关字段:

(1)Access-Control-Allow-Methods
该字段必需,它的值是逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法。注意,返回的是所有支持的方法,而不单是浏览器请求的那个方法。这是为了避免多次"预检"请求。
(2)Access-Control-Allow-Headers
如果浏览器请求包括 Access-Control-Request-Headers 字段,则 Access-Control-Allow-Headers 字段是必需的。它也是一个逗号分隔的字符串,表明服务器支持的所有头信息字段,不限于浏览器在预检中请求的字段。
(3)Access-Control-Max-Age
该字段可选,用来指定本次预检请求的有效期,单位为秒。上面结果中,有效期是 1800 秒,即允许缓存该条响应 1800 秒,在此期间,不用发出另一条预检请求。
(4)Access-Control-Allow-Credentials
该字段与简单请求时的含义相同。
(5)Access-Control-Expose-Headers
该字段与简单请求时的含义相同。

1.3.3、预检请求后简单请求

一旦服务器通过了预检请求,以后每次浏览器正常的 CORS 请求,就都跟简单请求一样。下面是预检请求之后,正常的 CORS 请求:

Cache-Control: no-cache
Connection: keep-alive
Content-Length: 11
Content-Type: application/x-www-form-urlencoded
Host: localhost:8081
my-request-header: 123
Origin: http://localhost:8080

服务器正常请求的响应:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Expose-Headers: my-response-header
Connection: keep-alive
Content-Length: 12
Content-Type: text/plain;charset=UTF-8

2、样例

2.1、后台实现(SpringBoot 版)

先编写后台 Controller:

package com.abc.demo.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/corstest")
@RestController
public class CorsTestController {
    @RequestMapping("/hello")
    public String hello(String name, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("my-request-header=" + request.getHeader("my-request-header"));
        response.addHeader("my-response-header","abc");
        return "hello," + name;
    }
}

使用 SpringBoot 来实现 CORS,有三种实现方式,选其中一种即可。

2.1.1、使用 @CrossOrigin 注解

在 Controller 中使用 @CrossOrigin 注解。

package com.abc.demo.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/corstest")
@RestController
public class CorsTestController {
    @CrossOrigin(origins = "http://localhost:8080",
            allowCredentials = "true",
            methods = {RequestMethod.GET, RequestMethod.POST},
            allowedHeaders = {"my-request-header", "my-request-header2", "content-type"},
            exposedHeaders = {"my-response-header"})
    @RequestMapping("/hello")
    public String hello(String name, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("my-request-header=" + request.getHeader("my-request-header"));
        response.addHeader("my-response-header","abc");
        return "hello," + name;
    }
}

2.1.2、实现 WebMvcConfigurer 接口

package com.abc.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST")
                .allowedOrigins("http://localhost:8080")
                .allowedHeaders("my-request-header", "my-request-header2", "content-type")
                .exposedHeaders("my-response-header")
                .allowCredentials(true);
    }
}

2.1.3、实现 Filter 接口

package com.abc.demo.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(filterName = "coreFilter", urlPatterns = "/*")
public class CoreFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Expose-Headers", "my-response-header");

        if (((HttpServletRequest) servletRequest).getMethod().equals("OPTIONS")) {
            response.addHeader("Access-Control-Allow-Methods", "GET,POST");
            response.addHeader("Access-Control-Allow-Headers", "my-request-header,my-request-header2,content-type");
            response.addHeader("Access-Control-Max-Age", "1800");
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

2.2、前台实现

2.2.1、原生写法(corstest.html)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cors 测试</title>

</head>
<body>
</body>

<script type="text/javascript">
    // IE8/9需用window.XDomainRequest兼容
    let xhr = new XMLHttpRequest(); 
     
    xhr.withCredentials = true;
    
    xhr.open('post', 'http://localhost:8081/corstest/hello', true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    //xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('my-request-header', '123');
    xhr.send('name=李白');
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText + "|" + xhr.getResponseHeader('my-response-header'));
        }
    }
</script>
</html>

2.2.2、Jquery写法(corstestJquery.html)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>cors 测试</title>

</head>
<body>
</body>
<script type="text/javascript" src="./jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(function(){
        $.ajax({
            url: 'http://localhost:8081/corstest/hello',
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            headers: {
                'my-request-header': '123'
            },
            data: {
                name: '李白'
            },
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(data, status, xhr) {
                alert(data + '|' + xhr.getResponseHeader('my-response-header'));
            }
        });
    });

</script>
</html>

3、测试

把 corstest.html 和 corstestJquery.html 放到 tomcat(端口:8080) 的 webapps\ROOT 下,并启动 SpringBoot 应用(端口:8081)。

 

 

参考:http://www.ruanyifeng.com/blog/2016/04/cors.html

posted @ 2021-07-04 10:00  且行且码  阅读(489)  评论(0编辑  收藏  举报