程序员SpringBoot极简教程 · Spring Boot

同源策略与CORS

2017-12-29  本文已影响244人  聪明的奇瑞

同源策略

URL OutCome Reason
http://store.company.com/dir2/other.html Success
http://store.company.com/dir/inner/anthoer.html Success
https://store.company.com/secure.html Failure Different protocol
http://store.company.com:81/dir/etc.html Failure Different port
http://news.company.com/dir/other.html Failure Different host
www.a.com/test.html:
    <body>
    {}body{font-family:
    aaaaaaaaaaaaaaa
    bbbbbbbbbbbbbbbbb
    </body>
www.b.com/test2.html:
    <style>
    @import url("http://www.a.com/test.html")
    </style>
    <script>
        setTimeout(function(){
            var t = document.body.currentStyle.fontFamily;
            alert(t);
        },2000);
    </script>

CORS

两种请求

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

简单请求

GET /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8

withCredentials 属性

Access-Control-Allow-Credentials = true
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.withCredentials = false;

非简单请求

var url = 'http://api.alice.com/cors';
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('X-Custom-Header', 'value');
xhr.send();
OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

预检请求的回应

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT  #表示支持的跨域请求方法
Access-Control-Allow-Headers: X-Custom-Header  #表示服务器支持的所有头信息字段
Access-Control-Allow-Credentials: true  #该字段与简单请求时相同
Access-Control-Max-Age: 1728000  #指定本次预检请求的有效期,单位为秒,即在缓存该条回应期间,不用在发出另一条预检请求
上一篇下一篇

猜你喜欢

热点阅读