关于同源策略和跨域访问的理解

来源:互联网 发布:国外健身社交软件 编辑:程序博客网 时间:2024/05/16 15:46

同源策略
理解跨域首先必须要了解同源策略。同源策略是浏览器上为安全性考虑实施的非常重要的安全策略。
何谓同源:
URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源。
同源策略:
浏览器的同源策略,限制了来自不同源的”document”或脚本,对当前”document”读取或设置某些属性。 (白帽子讲web安全[1])
从一个域上加载的脚本不允许访问另外一个域的文档属性。

举个例子:    比如一个恶意网站的页面通过iframe嵌入了银行的登录页面(二者不同源),如果没有同源限制,恶意网页上的javascript脚本就可以在用户登录银行的时候获取用户名和密码。在浏览器中,<script>、<img>、<iframe>、<link>等标签都可以加载跨域资源,而不受同源限制,但浏览器限制了JavaScript的权限使其不能读、写加载的内容。另外同源策略只对网页的HTML文档做了限制,对加载的其他静态资源如javascript、css、图片等仍然认为属于同源。代码示例(http://localhost:8080/和http://localhost:8081由于端口不同而不同源):
http://localhost:8080/test.html          <html>              <head><title>test same origin policy</title></head>              <body>                  <iframe id="test" src="http://localhost:8081/test2.html"></iframe>                  <script type="text/javascript">                      document.getElementById("test").contentDocument.body.innerHTML = "write somthing";                  </script>              </body>          </html>  http://localhost:8081/test2.html          <html>              <head><title>test same origin policy</title></head>              <body>                  Testing.              </body>          </html>  
在Firefox中会得到如下错误:    Error: Permission denied to access property 'body'Document对象的domain属性存放着装载文档的服务器的主机名,可以设置它。例如来自"blog.csdn.net"和来自"bbs.csdn.net"的页面,都将document.domain设置为"csdn.net",则来自两个子域名的脚本即可相互访问。

JSONP
JSONP技术实际和Ajax没有关系。我们知道

<script src="http://localhost:8081/test_data.js">      <script>          function test_handler(data) {              console.log(data);          }  </script>  
服务器端的Javascript脚本(http://localhost:8081/test_data.js):
 test_handler('{"data": "something"}');
为了动态实现JSONP请求,可以使用Javascript动态插入<script>标签:
<script type="text/javascript">          // this shows dynamic script insertion          var script = document.createElement('script');          script.setAttribute('src', url);          // load the script          document.getElementsByTagName('head')[0].appendChild(script);   </script>  
JSONP协议封装了上述步骤,jQuery中统一是现在AJAX中(其中data type为JSONP):http://localhost:8080/test?callback=test_handler为了支持JSONP协议,服务器端必须提供特别的支持[2],另外JSONP只支持GET请求。

参考博客
同源策略和跨域访问

原创粉丝点击