同源策略和跨域知識點學習

問題起因是在使用weibo api的時候,發現有一個報錯。weibo api是https協議,我本地是模擬的回調域名,然後進行數據通信,本地http協議,於是乎就報錯了。出於對postMessage的不是很熟悉,藉此機會學習晚上一些自己的知識儲備。

api.weibo.com/2/oauth2/authorize?client_id=******&response_type=token&d…ansport=html5&referer=http://www.unofficial.cn/demo/vuejs/demo.html:1 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.unofficial.cn') does not match the recipient window's origin ('http://www.unofficial.cn').

同源策略

在這之前需要先熟悉一下這個概念,同源指請求協議相同,主機名相同,端口相同,涉及安全的策略。

    // 例如我的博客地址
    http://www.unofficial.cn/demo/postMessage/pm1.html      同
    http://www.unofficial.cn/demo/vuejs/index.html          同
    https://www.unofficial.cn/demo/postMessage/pm1.html     不同 協議不同
    http://blog.unofficial.cn/demo/postMessage/pm1.html     不同 主機名不同
    http://www.unofficial.cn:8080/demo/postMessage/pm1.html 不同 端口不同

允許跨域寫

表單提交,例如我模擬了一個表單提交到我的一個其它站點。
同源策略主要限制的是不同源之間的交互操作,對於跨域內嵌的資源不受該策略限制。

允許跨域嵌入

  • <script src="……"> 標籤嵌入腳本,語法錯誤信息只能在同源腳本中捕捉到(?)。
  • <link rel="stylesheet" href="……"> 標籤嵌入css
  • <img src="" alt=""> 標籤嵌入圖片
  • <video> 和 標籤嵌入多媒體資源
  • @font-face
  • <iframe src="……" frameborder="0"> 載入的任何資源。可以使用x-frame-options消息頭來阻止這種形式的交互。

不允許跨域讀

需要注意的是,頁面內的引入的文件的域並不重要,重要的是加載該文件的頁面所在的域。例如說我在博客的首頁引入了 //cdn.bootcss.com/jquery/3.1.1/jquery.min.js 的jquery文件,這時 jquery.min.js 的源應該就是我的博客地址 http://www.unofficial.cn 。

iframe

同域可讀可寫,跨域可讀不可寫

// 請求地址://www.unofficial.cn/demo/postmessage/pm2.html
<iframe src="pm2.html" frameborder="0"></iframe>
<iframe src="//blog.unofficial.cn/demo/postmessage/pm2.html" frameborder="0"></iframe>
<script>
    window.onload = function() { // 必須等待文檔加載結束才能獲取
        var iframe = document.getElementsByTagName('iframe');
        console.log(iframe[0].contentDocument); // 同源
        console.log(iframe[1].contentDocument); // 不同源
    }
</script>
// 不同源時使用contentWindow/contentDocument報錯
// pm1.html:12 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://www.unofficial.cn" from accessing a cross-origin frame.(…)
  • 同源
    iframe外部操作,主要通過contentDocument/contentWindow,iframe內部使用window.parent,如果只是嵌套了一層可以使用window.top,iframe多層嵌套可以使用window.frameElement
    // 外部 -> 內

    var iframe = document.getElementsByTagName('iframe');
    // 舉例第一個
    iframe[0].contentDocument.getElementById('test').innerText = 123;

    // 內部 -> 外
    window.parent.getElementById('test').innerText = 123;
  • 跨域
    如果需要在跨域的情況下傳遞參數怎麼操作呢?
    iframe內部操作,主要通過 location.hash
    // 外部傳遞一個123給內部
    var src = iframe[0].src;
    iframe[0].src = src.indexOf('#') != -1 ? src.split('#')[0].concat('#', 123) : src.concat('#', 123);
    // 然後內部監測hashChange,自動獲取hash值

    // 內部更改hash
    window.location.hash = 123;
    // 但是如何外部如何監控src的變化呢?

ajax

cors

同域可讀可寫,跨域請求不能檢查到 Access-Control-Allow-Origin 的情況下會被攔截。

    // www.unofficial.cn:4000
    // 跨域請求
    var url = "http://www.unofficial.cn/demo.php";
    var params = "lorem=ipsum&name=binny";

    var http = new XMLHttpRequest();
    http.open("POST", url, true);
    
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(params);

XMLHttpRequest cannot load http://www.unofficial.cn/demo.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.unofficial.cn:4000' is therefore not allowed access.

上面錯誤提示可以設置 Access-Control-Allow-Origin ,於是在header中添加設置即可實現跨域請求。

options

  • Access-Control-Allow-Origin
    origin參數指定一個允許向該服務器提交請求的URI.對於一個不帶有credentials的請求,可以指定爲'*',表示允許來自所有域的請求。
    Access-Control-Allow-Origin: http://www.unofficial.cn

  • Access-Control-Allow-Credentials
    它的值是一個布爾值,表示是否允許發送Cookie。默認是 true 允許的。 『實際測試沒發現,也許是方法還不對吧。』

  • Access-Control-Expose-Headers
    設置瀏覽器允許訪問的服務器的頭信息的白名單。如果沒有設置白名單的,默認情況下只能獲取 Cache-ControlContent-LanguageContent-TypeExpiresLast-ModifiedPragma的值,沒設置返回 null,否則會得到以下提示:

    Refused to get unsafe header "X-Powered-By"

    例如:
    // 服務端設置 Access-Control-Expose-Headers: X-Powered-By

    前端可以這樣獲取到 X-Powered-By 的屬性值

        var http = new XMLHttpRequest();
    
        http.getResponseHeader('X-Powered-By'); // 
  • Access-Control-Max-Age
    設置預請求時間。即是設置 OPTION 的時間。

  • Access-Control-Allow-Methods
    設置允許的請求方法。

jsonp

cors的方式可以發起post請求,或者說其它形式的請求,但是jsonp只能使用get的方式獲取數據。

<script>
    function abc(data) {
        console.log(data);
    }abc('{"abc":"123"}');
</script>

<script src="http://www.unofficial.cn/test/demo.php?callback=abc"></script>

簡單說就是定義好回調處理方法,把回調函數的名稱傳遞給後端,後端拿到數據名稱後返回會的數據就是對於回調方法的執行。

<script src="http://www.unofficial.cn/test/demo.js"></script>
/**
 * demo.js的內容
 * abc({"abc":"123"});
 */

什麼是postMessage

postMessage是window對象的一個屬性,widow.postMessage是一個安全的跨源通信協議。當且僅當執行腳本的頁面使用相同的協議(通常都是 http)、相同的端口(http默認使用80端口)和相同的 host(兩個頁面的 document.domain 的值相同)時,才允許不同頁面上的腳本互相訪問。 window.postMessage 提供了一個可控的機制來安全地繞過這一限制,當其在正確使用的情況下。

  • iframe的情況下我們可以這樣使用,等待頁面加載結束時傳參數到指定源。
    ```
    // localhost ① pm1.html頁面中存在一個跨域iframe引用

    // www.unofficial.cn pm2.html中我們跨域監聽 message 獲取 postmessage 傳過來的數據。

    ```

  • window.open的情況下就需要特殊處理一下了
    // localhost ② window.open <script> function openAPage() { // 同源的情況下可以判斷頁面是否加載結束 var openPage = window.open('//localhost/demo/postMessage/pm2.html'); openPage.onload = function() { openPage.postMessage('some messages', '*'); } // 不同源的情況下,使用setTimeout或者setInterval var openPage = window.open('//www.unofficial.com/demo/postMessage/pm2.html'); setTimeout(function() { openPage.postMessage('some messages', '*'); }, 0) } </script>

    延遲多長時間執行?頁面加載時間是多長,這個不是很好判斷,setTimeout需要略估計一個時間,待open的頁面加載完成了再postMessage(應該不比完全加載就可以postMessage了)。要不然就是定時器,定時推一次,直接觸發事件後使用window.opener取消定時器。

總結

問題基本都是在過程中發現一個學習一個,對於沒有太多場景的學習,只能這樣慢慢積累。

參考資料

  • https://developer.mozilla.org/zh-CN/docs/Web/Security/Same-origin_policy
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章