是否可以提出安全的JSONP请求?

时间:2013-05-21 00:07:15

标签: javascript jsonp

我只需支持new browsers

我必须依赖外部服务来提供JSONP数据,我不拥有该服务而且它不允许CORS

我不得不相信来自外部服务器的JSONP请求,因为他们可以在我的终端上运行任意代码,这样他们就可以跟踪我的用户,甚至窃取他们的信息。

我想知道是否有办法创建一个安全的JSONP请求?

(相关:How to reliably secure public JSONP requests?但新浏览器不放松)

注意:我问/答答了Q& A风格,但我对其他想法非常开放。

1 个答案:

答案 0 :(得分:11)

是!

有可能。一种方法是使用WebWorkers。在WebWorkers中运行的代码无法访问您的页面正在运行的DOM或其​​他JavaScript代码。

您可以创建WebWorker并使用它执行JSONP请求,然后在完成后终止它。

这个过程是这样的:

  • 使用要请求的URL

  • 从blob创建WebWorker
  • 使用importScripts加载带有本地回调的JSONP请求

  • 当该回调执行时,将一条消息发回给脚本,然后脚本将执行带有数据的实际回调消息。

这样,攻击者就没有关于DOM的信息。

这是sample implementation

//   Creates a secure JSONP request using web workers.
//   url - the url to send the request to
//   data - the url parameters to send via querystring
//   callback - a function to execute when done
function jsonp(url, data, callback) {
    //support two parameters
    if (typeof callback === "undefined") {
        callback = data;
        data = {};
    }
    var getParams = ""; // serialize the GET parameters
    for (var i in data) {
        getParams += "&" + i + "=" + data[i];
    }
    //Create a new web worker, the worker posts a message back when the JSONP is done
    var blob = new Blob([
        "var cb=function(val){postMessage(val)};" +
        "importScripts('" + url + "?callback=cb" + getParams + "');"],{ type: "text/javascript" });
    var blobURL = window.URL.createObjectURL(blob);
    var worker = new Worker(blobURL);

    // When you get a message, execute the callback and stop the WebWorker
    worker.onmessage = function (e) {
        callback(e.data);
        worker.terminate();
        };
    worker.postMessage(getParams); // Send the request
    setTimeout(function(){
        worker.terminate();//terminate after 10 seconds in any case.
    },10000);
};

以下是适用于JSFiddle的示例用法:

jsonp("http://jsfiddle.net/echo/jsonp", {
    "hello": "world"
}, function (response) {
    alert(response.hello);
});

此实现不会处理其他一些问题但会阻止对页面上的DOM或当前JavaScript的所有访问,可以创建safe WebWorker environment

这适用于IE10 +,Chrome,Firefox和Safari以及移动浏览器。