From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../web/security/same-origin_policy/index.html | 117 +++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 files/zh-tw/web/security/same-origin_policy/index.html (limited to 'files/zh-tw/web/security/same-origin_policy') diff --git a/files/zh-tw/web/security/same-origin_policy/index.html b/files/zh-tw/web/security/same-origin_policy/index.html new file mode 100644 index 0000000000..9c80f3e435 --- /dev/null +++ b/files/zh-tw/web/security/same-origin_policy/index.html @@ -0,0 +1,117 @@ +--- +title: 同源政策 (Same-origin policy) +slug: Web/Security/Same-origin_policy +translation_of: Web/Security/Same-origin_policy +--- +

同源政策限制了程式碼和不同網域資源間的互動。

+ +

同源定義

+ +

所謂同源是指兩份網頁具備相同協定、埠號 (如果有指定) 以及主機位置,下表提供了一些例子展示那些來源和http://store.company.com/dir/page.html屬於同源:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
URLOutcomeReason
http://store.company.com/dir2/other.html同源
http://store.company.com/dir/inner/another.html同源
https://store.company.com/secure.html不同源協定不同
http://store.company.com:81/dir/etc.html不同源埠號不同
http://news.company.com/dir/other.html不同源主機位置不同
+ +

另外請參考 file來源定義: URL

+ +

Cookie 的來源定義和上述不一樣。

+ +

變更來源

+ +

網頁能夠有限地變更來源,我們可以將 {{domxref("document.domain")}} 存為目前網域後半部,然後較短的網域就會作為之後來源檢查,譬如我們在 http://store.company.com/dir/other.html 的文件裡執行以下程式碼:

+ +
document.domain = "company.com";
+
+ +

執行完後,網頁能以 http://company.com/dir/page.html 通過同源檢查。然而基於同源檢查,company.com 無法將 document.domain 存為 othercompany.com。

+ +

任何變更 document.domain 行為,包括 document.domain = document.domain 都會導致埠號重置為 null,因此無法只藉由執行 document.domain = "company.com" 讓company.com:8080 和 company.com 互動,必須兩邊都重新設定好讓埠號都一致重置為 null。

+ +
+

Note: 為了讓子網域可以安全的存取其母網域,我們需要一起改變子、母網域的document.domain 為相同值,即使只是將母網域設回原始值也是必要,否則將會導致許可權錯誤 (Permission Error)。

+
+ +

跨來源網路存取

+ +

同源政策控制了兩個不同網域來源互動,例如當使用{{domxref("XMLHttpRequest")}}。這些互動可分為以下三類:

+ + + +

下面是一些能跨來源嵌入的資源:

+ + + +

如何允許跨來源存取

+ +

使用CORS允許跨來源存取

+ +

如何阻擋跨來源存取

+ + + +

跨來源程式腳本存取

+ +

Javascript API例如iframe.contentWindow, {{domxref("window.parent")}}, {{domxref("window.open")}}以及{{domxref("window.opener")}},允許文件之間直接互相參照,當兩份文件的來源不同,參照存取WindowLocation物件將受到限制;一些瀏覽器比規範准許存取更多屬性。文件間的溝通也可以改用{{domxref("window.postMessage")}}來進行。

+ +

延伸閱讀

+ + + +
+

Original Document Information

+ + +
-- cgit v1.2.3-54-g00ecf