当前位置: 移动技术网 > IT编程>开发语言>.net > CORS讲解

CORS讲解

2019年05月09日  | 移动技术网IT编程  | 我要评论

禹城市房管局,isis恐怖组织,王力宏火力全开

 

跨域资源共享(cors) 是一种机制,它使用额外的 http 头来告诉浏览器  让运行在一个 origin (domain) 上的web应用被准许访问来自不同源服务器上的指定的资源。当一个资源从与该资源本身所在的服务器不同的域、协议或端口请求一个资源时,资源会发起一个跨域 http 请求

 

 

什么情况下需要 cors ?

  •  xmlhttprequest 或 fetch 发起的跨域 http 请求。
  • web 字体 (css 中通过 @font-face 使用跨域字体资源), 。
  • webgl 贴图
  • 使用 drawimage 将 images/video 画面绘制到 canvas
  • 样式表(使用 cssom

 

功能概述

跨域资源共享标准新增了一组 http 首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源。

另外,规范要求,对那些可能对服务器数据产生副作用的 http 请求方法(特别是 get 以外的 http 请求,或者搭配某些 mime 类型的 post 请求),

浏览器必须首先使用 options 方法发起一个预检请求(preflight request),从而获知服务端是否允许该跨域请求。

服务器确认允许之后,才发起实际的 http 请求。

在预检请求的返回中,服务器端也可以通知客户端,是否需要携带身份凭证(包括 cookies 和 http 认证相关数据)。

 

若干访问控制场景

简单请求

某些请求不会触发 cors 预检请求。本文称这样的请求为“简单请求”。

若请求满足所有下述条件,则该请求可视为“简单请求”:

 

注意: 这些跨域请求与浏览器发出的其他跨域请求并无二致。如果服务器未返回正确的响应首部,则请求方不会收到任何数据。因此,那些不允许跨域请求的网站无需为这一新的 http 访问控制特性担心。

 

比如说,假如站点 http://foo.example 的网页应用想要访问 http://bar.other 的资源。http://foo.example 的网页中可能包含类似于下面的 javascript 代码:

var invocation = new xmlhttprequest();
var url = 'http://bar.other/resources/public-data/';
   
function callotherdomain() {
  if(invocation) {    
    invocation.open('get', url, true);
    invocation.onreadystatechange = handler;
    invocation.send(); 
  }
}

客户端和服务器之间使用 cors 首部字段来处理跨域权限:

 

 分别检视请求报文和响应报文:

 1 get /resources/public-data/ http/1.1
 2 host: bar.other
 3 user-agent: mozilla/5.0 (macintosh; u; intel mac os x 10.5; en-us; rv:1.9.1b3pre) gecko/20081130 minefield/3.1b3pre
 4 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
 5 accept-language: en-us,en;q=0.5
 6 accept-encoding: gzip,deflate
 7 accept-charset: iso-8859-1,utf-8;q=0.7,*;q=0.7
 8 connection: keep-alive
 9 referer: http://foo.example/examples/access-control/simplexsinvocation.html
10 origin: http://foo.example
11 
12 
13 http/1.1 200 ok
14 date: mon, 01 dec 2008 00:23:53 gmt
15 server: apache/2.0.61 
16 access-control-allow-origin: *
17 keep-alive: timeout=2, max=100
18 connection: keep-alive
19 transfer-encoding: chunked
20 content-type: application/xml
21 
22 [xml data]

第 1~10 行是请求首部。第10行 的请求首部字段 origin 表明该请求来源于 http://foo.exmaple

第 13~22 行是来自于 http://bar.other 的服务端响应。响应中携带了响应首部字段 access-control-allow-origin(第 16 行)。

使用 origin 和 access-control-allow-origin 就能完成最简单的访问控制。

本例中,服务端返回的 access-control-allow-origin: * 表明,该资源可以被任意外域访问。

 

如果服务端仅允许来自 http://foo.example 的访问,该首部字段的内容如下:

access-control-allow-origin: http://foo.example

现在,除了 http://foo.example,其它外域均不能访问该资源(该策略由请求首部中的 origin 字段定义,见第10行)。

access-control-allow-origin 应当为 * 或者包含由 origin 首部字段所指明的域名。

 

预检请求

 与前述简单请求不同,“需预检的请求”要求必须首先使用 options   方法发起一个预检请求到服务器,以获知服务器是否允许该实际请求。

"预检请求“的使用,可以避免跨域请求对服务器的用户数据产生未预期的影响

请求满足下述任一条件时,即应首先发送预检请求:

 

如下是一个需要执行预检请求的 http 请求:

 1 var invocation = new xmlhttprequest();
 2 var url = 'http://bar.other/resources/post-here/';
 3 var body = '<?xml version="1.0"?><person><name>arun</name></person>';
 4     
 5 function callotherdomain(){
 6   if(invocation)
 7     {
 8       invocation.open('post', url, true);
 9       invocation.setrequestheader('x-pingother', 'pingpong');
10       invocation.setrequestheader('content-type', 'application/xml');
11       invocation.onreadystatechange = handler;
12       invocation.send(body); 
13     }
14 }
15 
16 ......

上面的代码使用 post 请求发送一个 xml 文档,该请求包含了一个自定义的请求首部字段(x-pingother: pingpong)。

另外,该请求的 content-type 为 application/xml。因此,该请求需要首先发起“预检请求”。

 

 

 

 1.options /resources/post-here/ http/1.1
 2.host: bar.other
 3.user-agent: mozilla/5.0 (macintosh; u; intel mac os x 10.5; en-us; rv:1.9.1b3pre) gecko/20081130 minefield/3.1b3pre
 4.accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
 5.accept-language: en-us,en;q=0.5
 6.accept-encoding: gzip,deflate
 7.accept-charset: iso-8859-1,utf-8;q=0.7,*;q=0.7
 8.connection: keep-alive
 9.origin: http://foo.example
10.access-control-request-method: post
11.access-control-request-headers: x-pingother, content-type
12.
13.
14.http/1.1 200 ok
15.date: mon, 01 dec 2008 01:15:39 gmt
16.server: apache/2.0.61 (unix)
17.access-control-allow-origin: http://foo.example
18.access-control-allow-methods: post, get, options
19.access-control-allow-headers: x-pingother, content-type
20.access-control-max-age: 86400
21.vary: accept-encoding, origin
22.content-encoding: gzip
23.content-length: 0
24.keep-alive: timeout=2, max=100
25.connection: keep-alive
26.content-type: text/plain

预检请求完成之后,发送实际请求:

post /resources/post-here/ http/1.1
host: bar.other
user-agent: mozilla/5.0 (macintosh; u; intel mac os x 10.5; en-us; rv:1.9.1b3pre) gecko/20081130 minefield/3.1b3pre
accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language: en-us,en;q=0.5
accept-encoding: gzip,deflate
accept-charset: iso-8859-1,utf-8;q=0.7,*;q=0.7
connection: keep-alive
x-pingother: pingpong
content-type: text/xml; charset=utf-8
referer: http://foo.example/examples/preflightinvocation.html
content-length: 55
origin: http://foo.example
pragma: no-cache
cache-control: no-cache

<?xml version="1.0"?><person><name>arun</name></person>


http/1.1 200 ok
date: mon, 01 dec 2008 01:15:40 gmt
server: apache/2.0.61 (unix)
access-control-allow-origin: http://foo.example
vary: accept-encoding, origin
content-encoding: gzip
content-length: 235
keep-alive: timeout=2, max=99
connection: keep-alive
content-type: text/plain

[some gzip'd payload]

浏览器检测到,从 javascript 中发起的请求需要被预检。从上面的报文中,我们看到,第 1~12 行发送了一个使用 options 方法的“预检请求”。

 options 是 http/1.1 协议中定义的方法,用以从服务器获取更多信息。

该方法不会对服务器资源产生影响。 预检请求中同时携带了下面两个首部字段:

access-control-request-method: post
access-control-request-headers: x-pingother, content-type

首部字段 access-control-request-method 告知服务器,实际请求将使用 post 方法。

首部字段 access-control-request-headers 告知服务器,实际请求将携带两个自定义请求首部字段:x-pingother 与 content-type。

服务器据此决定,该实际请求是否被允许。

 

第14~26 行为预检请求的响应,表明服务器将接受后续的实际请求。重点看第 17~20 行:

access-control-allow-origin: http://foo.example
access-control-allow-methods: post, get, options
access-control-allow-headers: x-pingother, content-type
access-control-max-age: 86400

首部字段 access-control-allow-methods 表明服务器允许客户端使用 post, get 和 options 方法发起请求。

首部字段 access-control-allow-headers 表明服务器允许请求中携带字段 x-pingother content-type

最后,首部字段 access-control-max-age 表明该响应的有效时间为 86400 秒,也就是 24 小时。在有效时间内,浏览器无须为同一请求再次发起预检请求。

 

预检请求与重定向

大多数浏览器不支持针对于预检请求的重定向。如果一个预检请求发生了重定向,浏览器将报告错误:

the request was redirected to 'https://example.com/foo', which is disallowed for cross-origin requests that require preflight
request requires preflight, which is disallowed to follow cross-origin redirect

在浏览器的实现跟上规范之前,有两种方式规避上述报错行为:

  • 在服务端去掉对预检请求的重定向;
  • 将实际请求变成一个简单请求。

如果上面两种方式难以做到,我们仍有其他办法:

不过,如果请求是由于存在 authorization 字段而引发了预检请求,则这一方法将无法使用。这种情况只能由服务端进行更改

 

附带身份凭证的请求

 fetch 与 cors 的一个有趣的特性是,可以基于  http cookies 和 http 认证信息发送身份凭证。

一般而言,对于跨域 xmlhttprequest 或 fetch 请求,浏览器不会发送身份凭证信息。

如果要发送凭证信息,需要设置 xmlhttprequest 的某个特殊标志位。

 

本例中,http://foo.example 的某脚本向 http://bar.other 发起一个get 请求,并设置 cookies:

var invocation = new xmlhttprequest();
var url = 'http://bar.other/resources/credentialed-content/';
    
function callotherdomain(){
  if(invocation) {
    invocation.open('get', url, true);
    invocation.withcredentials = true;
    invocation.onreadystatechange = handler;
    invocation.send(); 
  }
}

第 7 行将 xmlhttprequest 的 withcredentials 标志设置为 true,从而向服务器发送 cookies。

因为这是一个简单 get 请求,所以浏览器不会对其发起“预检请求”。

但是,如果服务器端的响应中未携带 access-control-allow-credentials: true ,浏览器将不会把响应内容返回给请求的发送者。

客户端与服务器端交互示例如下:

 1 get /resources/access-control-with-credentials/ http/1.1
 2 host: bar.other
 3 user-agent: mozilla/5.0 (macintosh; u; intel mac os x 10.5; en-us; rv:1.9.1b3pre) gecko/20081130 minefield/3.1b3pre
 4 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
 5 accept-language: en-us,en;q=0.5
 6 accept-encoding: gzip,deflate
 7 accept-charset: iso-8859-1,utf-8;q=0.7,*;q=0.7
 8 connection: keep-alive
 9 referer: http://foo.example/examples/credential.html
10 origin: http://foo.example
11 cookie: pageaccess=2
12 
13 
14 http/1.1 200 ok
15 date: mon, 01 dec 2008 01:34:52 gmt
16 server: apache/2.0.61 (unix) php/4.4.7 mod_ssl/2.0.61 openssl/0.9.7e mod_fastcgi/2.4.2 dav/2 svn/1.4.2
17 x-powered-by: php/5.2.6
18 access-control-allow-origin: http://foo.example
19 access-control-allow-credentials: true
20 cache-control: no-cache
21 pragma: no-cache
22 set-cookie: pageaccess=3; expires=wed, 31-dec-2008 01:34:53 gmt
23 vary: accept-encoding, origin
24 content-encoding: gzip
25 content-length: 106
26 keep-alive: timeout=2, max=100
27 connection: keep-alive
28 content-type: text/plain
29 
30 
31 [text/plain payload]

即使第 11 行指定了 cookie 的相关信息,但是,如果 bar.other 的响应中缺失 access-control-allow-credentials: true(第 19 行),则响应内容不会返回给请求的发起者。

 

附带身份凭证的请求与通配符

对于附带身份凭证的请求,服务器不得设置 access-control-allow-origin 的值为“*”。

这是因为请求的首部中携带了 cookie 信息,如果 access-control-allow-origin 的值为“*”,请求将会失败。

而将 access-control-allow-origin 的值设置为 http://foo.example,则请求将成功执行。

 

另外,响应首部中也携带了 set-cookie 字段,尝试对 cookie 进行修改。如果操作失败,将会抛出异常。

 

http 响应首部字段

access-control-allow-origin

access-control-allow-origin: <origin> | *

 

其中,origin 参数的值指定了允许访问该资源的外域 uri。对于不需要携带身份凭证的请求,服务器可以指定该字段的值为通配符,表示允许来自所有域的请求。

 

access-control-expose-headers

在跨域访问时,xmlhttprequest对象的getresponseheader()方法只能拿到一些最基本的响应头,cache-control、content-language、content-type、expires、last-modified、pragma,如果要访问其他头,则需要服务器设置本响应头。

access-control-expose-headers 头让服务器把允许浏览器访问的头放入白名单,例如:

access-control-expose-headers: x-my-custom-header, x-another-custom-header

这样浏览器就能够通过getresponseheader访问x-my-custom-header和 x-another-custom-header 响应头了

 

access-control-max-age

access-control-max-age 头指定了preflight请求的结果能够被缓存多久

access-control-max-age: <delta-seconds>

delta-seconds 参数表示preflight请求的结果在多少秒内有效。

 

access-control-allow-credentials

access-control-allow-credentials 头指定了当浏览器的credentials设置为true时是否允许浏览器读取response的内容。

当用在对preflight预检测请求的响应中时,它指定了实际的请求是否可以使用credentials

请注意:简单 get 请求不会被预检;如果对此类请求的响应中不包含该字段,这个响应将被忽略掉,并且浏览器也不会将相应内容返回给网页。

 

access-control-allow-credentials: true

 

access-control-allow-methods

access-control-allow-methods 首部字段用于预检请求的响应。其指明了实际请求所允许使用的 http 方法。

access-control-allow-methods: <method>[, <method>]*

 

access-control-allow-headers

access-control-allow-headers 首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段。

access-control-allow-headers: <field-name>[, <field-name>]*

 

http 请求首部字段

 

做记录

参考网址

https://developer.mozilla.org/zh-cn/docs/web/http/access_control_cors

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网