规避同源策略的方法 [英] Ways to circumvent the same-origin policy

查看:25
本文介绍了规避同源策略的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同源政策

我想制作一个关于 HTML/JS 同源策略的社区维基,希望能帮助任何搜索此主题的人.这是 SO 上搜索次数最多的主题之一,并且没有统一的 wiki,所以我在这里 :)

<块引用>

同源策略防止从一个加载的文档或脚本起源于获取或设置来自另一个文档的属性起源.这项政策一直沿用至今回到 Netscape Navigator 2.0.

您最喜欢绕过同源策略的一些方法是什么?

请保持示例详细,最好还链接您的来源.

解决方案

document.domain 方法

  • 方法类型:iframe.

请注意,这是一个 iframe 方法,它将 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.

使用此方法,您将被允许从源自主域的页面上的子域上的 iframe 执行 javascript.此方法不适用于跨域资源,因为 Firefox 等浏览器不允许您将 document.domain 更改为完全陌生的域.

来源:https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript>

跨域资源共享方法

  • 方法类型:AJAX.

跨源资源共享 (CORS) 是 W3C 工作草案定义浏览器和服务器在跨源访问源时必须如何通信.CORS 背后的基本思想是使用自定义 HTTP 标头,让浏览器和服务器充分了解彼此,以确定请求或响应是成功还是失败.

对于一个简单的请求,使用 GETPOST 没有自定义标头且主体为 text/plain,请求发送时带有一个名为 Origin 的额外标头.Origin 标头包含请求页面的来源(协议、域名和端口),以便服务器可以轻松确定它是否应该提供响应.示例 Origin 标头可能如下所示:

来源:http://www.stackoverflow.com

如果服务器决定应该允许请求,它会发送一个 Access-Control-Allow-Origin 标头回显发送的相同来源或 * 如果这是一种公共资源.例如:

Access-Control-Allow-Origin:http://www.stackoverflow.com

如果此标头丢失,或来源不匹配,则浏览器将拒绝该请求.如果一切顺利,浏览器就会处理请求.请注意,请求和响应都不包含 cookie 信息.

Mozilla 团队在 他们关于 CORS 的帖子中提出了建议 您应该检查 withCredentials 属性是否存在,以确定浏览器是否通过 XHR 支持 CORS.然后你可以结合 XDomainRequest 对象的存在来覆盖所有浏览器:

function createCORSRequest(method, url){var xhr = new XMLHttpRequest();如果(xhr 中的withCredentials"){xhr.open(方法,网址,真);} else if (typeof XDomainRequest != "undefined"){xhr = 新的 XDomainRequest();xhr.open(方法,网址);} 别的 {xhr = 空;}返回 xhr;}var request = createCORSRequest("get", "http://www.stackoverflow.com/");如果(请求){request.onload = function() {//...};request.onreadystatechange = 处理程序;request.send();}

请注意,要使 CORS 方法起作用,您需要有权访问任何类型的服务器标头机制,而不能简单地访问任何第三方资源.

来源:http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

window.postMessage 方法

  • 方法类型:iframe.

window.postMessage 被调用时,会在任何必须执行的挂起脚本完成时(例如剩余的事件处理程序,如果 window.postMessage 从事件处理程序、先前设置的挂起超时等中调用).MessageEvent 具有消息类型,一个 data 属性设置为提供给 window.postMessage 的第一个参数的字符串值,一个 origin 属性对应于调用 window.postMessage 时调用 window.postMessage 的窗口中主文档的来源,以及一个 source 属性,它是调用 window.postMessage 的窗口.

要使用window.postMessage,必须附加一个事件监听器:

//Internet Explorerwindow.attachEvent('onmessage',receiveMessage);//Opera/Mozilla/Webkitwindow.addEventListener("message", receiveMessage, false);

并且必须声明一个 receiveMessage 函数:

function receiveMessage(event){//用 event.data 做一些事情;}

场外 iframe 还必须通过 postMessage 正确发送事件:

任何窗口都可以在任何其他窗口上访问此方法,无论文档在窗口中的位置如何,都可以随时向其发送消息.因此,任何用于接收消息的事件侦听器都必须首先使用来源和可能的来源属性检查消息发送者的身份.这一点不能低估:未能检查 origin 和可能的 source 属性会导致跨站点脚本攻击.

来源:https://developer.mozilla.org/en/DOM/window.postMessage

The same origin policy

I wanted to make a community wiki regarding HTML/JS same-origin policies to hopefully help anyone searching for this topic. This is one of the most searched-for topics on SO and there is no consolidated wiki for it so here I go :)

The same origin policy prevents a document or script loaded from one origin from getting or setting properties of a document from another origin. This policy dates all the way back to Netscape Navigator 2.0.

What are some of your favorite ways to go around same-origin policies?

Please keep examples verbose and preferably also link your sources.

解决方案

The document.domain method

  • Method type: iframe.

Note that this is an iframe method that sets the value of document.domain to a suffix of the current domain. If it does so, the shorter domain is used for subsequent origin checks. For example, assume a script in the document at http://store.company.com/dir/other.html executes the following statement:

document.domain = "company.com";

After that statement executes, the page would pass the origin check with http://company.com/dir/page.html. However, by the same reasoning, company.com could not set document.domain to othercompany.com.

With this method, you would be allowed to exectue javascript from an iframe sourced on a subdomain on a page sourced on the main domain. This method is not suited for cross-domain resources as browsers like Firefox will not allow you to change the document.domain to a completely alien domain.

Source: https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript

The Cross-Origin Resource Sharing method

  • Method type: AJAX.

Cross-Origin Resource Sharing (CORS) is a W3C Working Draft that defines how the browser and server must communicate when accessing sources across origins. The basic idea behind CORS is to use custom HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail.

For a simple request, one that uses either GET or POST with no custom headers and whose body is text/plain, the request is sent with an extra header called Origin. The Origin header contains the origin (protocol, domain name, and port) of the requesting page so that the server can easily determine whether or not it should serve a response. An example Origin header might look like this:

Origin: http://www.stackoverflow.com

If the server decides that the request should be allowed, it sends a Access-Control-Allow-Origin header echoing back the same origin that was sent or * if it’s a public resource. For example:

Access-Control-Allow-Origin: http://www.stackoverflow.com

If this header is missing, or the origins don’t match, then the browser disallows the request. If all is well, then the browser processes the request. Note that neither the requests nor responses include cookie information.

The Mozilla team suggests in their post about CORS that you should check for the existence of the withCredentials property to determine if the browser supports CORS via XHR. You can then couple with the existence of the XDomainRequest object to cover all browsers:

function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

var request = createCORSRequest("get", "http://www.stackoverflow.com/");
if (request){
    request.onload = function() {
        // ...
    };
    request.onreadystatechange = handler;
    request.send();
}

Note that for the CORS method to work, you need to have access to any type of server header mechanic and can't simply access any third-party resource.

Source: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

The window.postMessage method

  • Method type: iframe.

window.postMessage, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes (e.g. remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.). The MessageEvent has the type message, a data property which is set to the string value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called.

To use window.postMessage, an event listener must be attached:

    // Internet Explorer
    window.attachEvent('onmessage',receiveMessage);

    // Opera/Mozilla/Webkit
    window.addEventListener("message", receiveMessage, false);

And a receiveMessage function must be declared:

function receiveMessage(event)
{
    // do something with event.data;
}

The off-site iframe must also send events properly via postMessage:

<script>window.parent.postMessage('foo','*')</script>

Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be understated: Failure to check the origin and possibly source properties enables cross-site scripting attacks.

Source: https://developer.mozilla.org/en/DOM/window.postMessage

这篇关于规避同源策略的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆