我有两个子域 content
和 www
域下example.com
.内容来自 content.example.com
正在www.example.com
中呈现通过 iframe。
因为content.example.com
上的内容需要联系www.example.com
我已经设置了 document.domain="example.com"
并设置 allow-scripts
和 allow-same-origin
在 iframe 上。
我担心如果用户可以上传要在 iframe 中显示的内容,它可能会被利用,即将 cookie 的内容发送到远程域以劫持 session 或其他安全漏洞。
我已经设置了另一个域,www.example2.com
并在 content.example.com
的 iframe 内容中放置一个 AJAX 请求测试我的理论并发送 document.cookie
到远程域。这导致 _ga
cookie 被发送到远程域。我已经允许 header('Access-Control-Allow-Origin: *')
在远程域上,所以它不会引起任何问题。
为什么只发送 _ga cookie?我在与 _ga cookie 相同的域和路径中还有许多其他 cookie,但它们没有发送。这样做是否存在其他安全风险?理想情况下,我希望只能在 content.example.com
之间进行通信和 www.example.com
看起来它主要是这样做的,除了 Google Analytics cookie,这意味着其他人也可以这样做。
最佳答案
无论跨域设置和策略如何,您都可以使用 JSONP 来通信不同的域。
但是 JSONP 要求服务器端以返回的数据作为参数构建回调函数。
我建议从服务器加载纯 Javascript 内容,它具有与 JSON 请求相同的跨域独立性和安全性。
假设您有一个 Javascript 文件,data.js
, 在 content.example.com
,或返回与响应中文件相同内容的服务,
使用 JSON 对象,前缀为变量赋值:
result = {
"string1": "text1",
"object1": {
"string2": "text2",
"number1": 5.6
},
"number2": 7,
"array1": ["text3", "text4"]
}
然后,在您的网页中,在
www.example.com
, 你可以有一个带有函数 loadJS
的脚本,它将服务器响应加载为脚本:
var loadJS = function (url, callback) {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = url;
script.onload = function (ev) {
callback(window.result);
delete window.result;
this.parentNode.removeChild(this);
};
document.body.appendChild(script);
};
window.onload = function () {
loadJS('http://content.example.com/data.js', function (data) {
console.log(data);
});
};
相同的功能可以在
content.example.com
中使用对于相反方向的请求。为了设置 cookie 或执行 JS 中可用的任何其他功能,
响应脚本,
data.js
, 可能包含一个函数而不是一个 JSON 对象:result = (function () {
document.cookie = "cookie1=Value1; cookie2=Value2;";
return true;
})();
关于在 iframe 内容中设置 document.domain 的安全隐患,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44147387/