2016-05-05 31 views
1

當使用document.domain來允許CORS時,似乎與訪問限制略有不一致。即,從A改變文檔域B繼續以允許跨源請求到A,但允許訪問I幀屬於A.與document.domain和CORS相關的這種不一致行爲的解釋是什麼?

考慮下面的例子:

<!-- b.html --> 
<html> 
    <head> 
    </head> 
</html> 

<!-- test.domain.com/a.html --> 
<html> 
    <head> 
    <script> 
     window.onload = function(e) { 
     document.domain = "domain.com"; 
     var iframe = document.createElement('iframe'); 
     document.body.appendChild(iframe); 
     iframe.onload = function(e) { 
      // This produces an access-denied error 
      console.log(iframe.contentWindow.location.href); 
     }; 

     $.ajax({url: "test.domain.com/b.html", success: function(result){ 
      console.log(result); // Will dump all of b.html 
     }}); 
     }; 
    </script> 
    </head> 
</html> 

這對我來說情況似乎很奇怪。一旦更改document.domain,對包含b.html的iframe的訪問受到限制,但對同一文檔的ajax調用不受限制。是否有這種不一致的原因?也就是說,即使在瀏覽器「知道」子框架和父框架都來自同一來源的情況下,瀏覽器爲什麼在訪問子框架時僅考慮document.domain

回答

2

document.domain影響按照HTML標準的原點的domain部分:https://html.spec.whatwg.org/multipage/browsers.html#dom-document-domain

然後,有些操作使用「相同來源」比較,有些操作使用「相同來源 - 域」比較。請參閱https://html.spec.whatwg.org/multipage/browsers.html#same-origin

後者僅用於某些傳統方案,因爲document.domain現在是網絡中相當不受歡迎的部分。因此,你會發現這些小的不一致。

+0

你可否詳細說一下爲什麼'document.domain'是不需要的?這似乎是連接來自不同子域的數據的相當有用的方式,例如'facebook.com'和'api.facebook.com'。是否應該只使用'postMessage'? – Max

+0

是的。通過使用'document.domain',你可以打開自己的攻擊。如果一個子域受到威脅,那麼你也是如此。如果有人在不知道此情況的情況下在某個子域上部署測試,那麼他們也會暴露其他人,等等。維護起源隔離是定位潛在攻擊媒介的好方法。 – Anne

相關問題