- Notifications
You must be signed in to change notification settings - Fork 709
CORS
JoyChou edited this page Dec 12, 2019 · 10 revisions
前端发起AJAX请求都会受到同源策略(CORS)的限制。发起AJAX请求的方法:
- XMLHttpRequest
- JQuery的
$.ajax - Fetch
前端在发起AJAX请求时,同域或者直接访问的情况下,因为没有跨域的需求,所以Request的Header中的Origin为空。此时,如果后端代码是response.setHeader("Access-Control-Allow-Origin", origin),那么Response的header中不会出现Access-Control-Allow-Origin,因为Origin为空。
<html> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"> </script> <body> <script> $.ajax({ type: "GET", url: "http://localhost:8080/cors/vuls2", success: function(data) { alert(data); }, error: function(msg) { alert(msg) } }); </script> </body> </html> - 同域的请求会自动带上Cookie。
- Origin为空,表示是同域或直接访问,视为安全情况。做安全限制需要注意空Origin,不要一起限制了。
- 后端设置
Access-Control-Allow-Origin为*的情况下,跨域的时候前端如果设置withCredentials为true会异常。The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. - 后端设置
Access-Control-Allow-Credentials为true,表示跨域请求后端接口时,允许带上Cookie。此时,前端必须设置withCredentials为true。同时,由于Cookie本身也受同源策略限制,所以Cookie要实现跨域,还需要满足:- 相同的一级域名(比如joychou.org)
- Cookie的domain设置为
.joychou.org
- 不能实现a.com带上Cookie跨域请求b.com,b.com的请求中头的Cookie不会存在a.com的Cookie。
测试在xxx.joychou.org跨域请求test.joychou.org,并且成功在test.joychou.org请求头里带上xxx.joychou.org的Cookie。相关步骤:
- xxx.joychou.org设置一个
aaa=bbb,domain为.joychou.org的Cookie - xxx.joychou.org的test.html,前端代码设置
withCredentials为true - test.joychou.org后端设置
Access-Control-Allow-Credentials为true - test.joychou.org后端设置
Access-Control-Allow-Origin为Origin里的值
http://xxx.joychou.org/test.html 代码:
<html> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"> </script> <body> <script> $.ajax({ type: "GET", url: "http://test.joychou.org", xhrFields: { withCredentials: true }, success: function(data) { alert(data); }, error: function(msg) { alert(msg) } }); </script> </body> </html>存在漏洞配置:
add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; add_header 'Access-Control-Allow-Credentials' 'true'; or
add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; add_header 'Access-Control-Allow-Credentials' 'true'; 修复方案需要限制origin:
add_header 'Access-Control-Allow-Origin' https://test.joychou.org; add_header 'Access-Control-Allow-Origin' http://test.joychou.org;