跨域之同源策略 Same-origin policy

同源策略是瀏覽器中最基本的隔離潛在惡意文件的安全策略,他限制了來自不一樣源(origin)的文檔或腳本之間的相互做用。html

何謂同源

跨域之URL中介紹過一個URL的標準格式以下:跨域

協議類型://服務器地址(必要時需加上端口號)/路徑/文件名瀏覽器

對比URL的標準格式,這裏的同源就是指:安全

  1. 協議類型相同(protocol)
  2. 服務器地址相同(host,也能夠叫域名相同)
  3. 端口相同(port,通常默認爲80)

下面是維基百科上的例子。服務器

假如一個URL爲http://www.example.com/dir/page.html,下表中列舉的URL與該URL的關係(Success表示同源,Failure表示不一樣源):dom

Compared URL Outcome Reason
http://www.example.com/dir/page2.html Success Same protocol, host and port
http://www.example.com/dir2/other.html Success Same protocol, host and port
http://username:password@www.example.com/dir2/other.html Success Same protocol, host and port
http://www.example.com:81/dir/other.html Failure Same protocol and host but different port
https://www.example.com/dir/other.html Failure Different protocol
http://en.example.com/dir/other.html Failure Different host
http://example.com/dir/other.html Failure Different host (exact match required)
http://v2.www.example.com/dir/other.html Failure Different host (exact match required)
http://www.example.com:80/dir/other.html Depends Port explicit. Depends on implementation in browser.

IE特例(摘自MDN)

在處理同源策略的問題上,IE存在兩個主要的不一樣之處。ide

  • 授信範圍(Trust Zones):兩個相互之間高度互信的域名,如公司域名(corporate domains),不遵照同源策略的限制。
  • 端口:IE未將端口號加入到同源策略的組成部分之中,所以 http://company.com:81/index.html 和http://company.com/index.html  屬於同源而且不受任何限制。

同源策略的限制

同源策略是爲了保證用戶信息的安全而設置的,若是兩個頁面不一樣源,他們在如下交互上受到限制(摘自瀏覽器同源政策及其規避方法):學習

  1. Cookie、LocalStorageIndexDB 沒法讀取。
  2. DOM 沒法得到。
  3. AJAX 請求不能成功。

有些時候爲了實現某些需求,能夠使用一些特殊手段突破同源策略的限制,在以後的學習中再總結。ui

相關文章
相關標籤/搜索