Analysis of cross-origin requests

Source: Internet
Author: User
Tags subdomain subdomain name
Preface

Recently, I encountered some cross-origin problems when I was working on the project, although I shared a lot of cross-origin problems online. However, it is still a bit confusing when I encounter it. After the project is launched, write an article to summarize it.

Cause of cross-Origin

The same-origin policy of the browser will cause cross-origin. Here, the same-origin policy is divided into the following two types:

  • Dom same-origin policy: do not perform operations on the DOM of different page sources. The main scenario here is cross-domain IFRAME. IFRAME of different domain names restricts mutual access.
  • XMLHttpRequest same-origin policy: Prohibit the use of xhr objects to initiate HTTP requests to different source server addresses.

As long as the Protocol, domain name, and port are any different, they are treated as different domains, and requests between them are cross-origin operations.

Why cross-origin restrictions?

After understanding cross-origin, I think everyone will think about this. Why is there a cross-origin restriction? Why does the browser do this. In fact, if you think about it, you will understand that cross-origin restrictions are mainly for security considerations.

The Ajax same-origin policy is mainly used to prevent csrf attacks. Without the Ajax same-origin policy, it is quite dangerous. Every HTTP request we initiate will carry the cookie corresponding to the request address, so we can perform the following attacks:

  1. The user logged on to his bank pagehttp://mybank.com,http://mybank.comAdds a user ID to a user's cookie.
  2. The user browsed malicious pages.http://evil.com. Executed the malicious Ajax Request Code on the page.
  3. http://evil.comDirectionhttp://mybank.comWhen an Ajax HTTP request is initiatedhttp://mybank.comThe cookie is also sent at the same time.
  4. The Bank page extracts the user ID from the sent cookie to verify that the user is correct. The request data is returned in response. In this case, the data is leaked.
  5. In addition, because Ajax is executed in the background, users cannot perceive this process.

The same applies to the same Dom same-origin policy. If IFRAME can be accessed across domains, the attack can be as follows:

  1. Create a fake website and use IFRAME to nest a bank websitehttp://mybank.com.
  2. Adjust the IFRAME width and height to all pages, so that there is no difference between the user's incoming domain name and other parts and the Bank's website.
  3. At this time, if the user enters the account password, our main website can accesshttp://mybank.comTo get the user input, then an attack is completed.

Therefore, with cross-origin and cross-domain restrictions, we can access the Internet more securely.

Cross-origin solution CORS)

CORS is a W3C standard, full name: "cross-origin Resource Sharing ).
For this method, the article summarized by instructor Ruan Yifeng is very good. For more information, see it.http://www.ruanyifeng.com/blog/2016/04/cors.html.

By adding an extension field to the HTTP header, the server adds a field to the header of the corresponding webpage to indicate the domain and HTTP method that can be accessed. The client checks whether its domain is in the allowed list, determines whether to process the response.

The basic implementation is that JavaScript cannot operate HTTP headers. Some browser plug-ins actually have this capability.

Add the server to the HTTP Response Header (page-level control mode ):

Access-control-allow-origin: example.com
Access-control-request-method: Get, post
Access-control-allow-headers: Content-Type, authorization, accept, range, Origin

Access-control-expose-headers: Content-Range

Access-control-max-age: 3600

Multiple Domain Names are separated by commas (,) to provide cross-origin access permissions for the domain names shown in. "*" Indicates that cross-domain access is allowed for all domain names.

The client can have two actions:

  1. Send the options request to request access-control information. If your domain name is in the allowed access list, a real request is sent; otherwise, the request is discarded.
  2. Send the request directly, and then check the access-control information of response. If your domain name is in the allowed access list, read the response body; otherwise, give up.

Essentially, the response content of the server has arrived locally, and JavaScript decides whether to read the content.

Here I will briefly introduce the general process.

  1. For the client, we still normally use the xhr object to send Ajax requests.
    The only thing to note is that we need to set our xhr attributes.withCredentialsIt is true. Otherwise, the cookie cannot be replaced. Set:xhr.withCredentials = true;
  2. For the server, you need to set the following two fields in the Response Header:
    Access-Control-Allow-Origin: http://www.yourhost.com
    Access-Control-Allow-Credentials:true
    In this way, we can use the cross-origin request interface.

In actual Django projects, CORS technology is used to build a middleware to solve cross-origin problems:

Class corsmiddleware (middlewaremixin): def process_response (self, request, response): "solve cross-domain problem: Param request: Param response: return: "# Add a response header # Allow your domain name to retrieve my data response ['access-control-allow-origin'] =" * "# Allow you to carry Content-Type request Header # response ['access-control-allow-headers'] = "Content-Type" # Allow you to send Delete, put # response ['access-control-allow-methods '] = "delete, put" return response
Jsonp implements cross-Origin

The basic principle is to dynamically create a script tag and then use the src attribute for cross-origin.
This is vague. Let's look at an example:

<SCRIPT> // define a fun function fun (data) {console. log (data) ;}// create a script and notify the backend callback function named fun var body = document. getelementsbytagname ('body') [0]; var script = document. createelement ('script'); script. type = 'text/JavaScript '; script. src = 'demo. JS? Callback = fun; body. appendchild (SCRIPT); </SCRIPT>

The returned JS script will be executed directly. So we executed the pre-defined fun function and passed in the data.

fun({"name":"name"})

Of course, this is just a schematic demonstration. In actual situations, we need to dynamically create this fun function and destroy it when the data is returned.

In actual use, the various Ajax libraries we use basically contain the jsonp encapsulation, but we still need to know the principle, otherwise, I don't know why jsonp cannot send a POST request ~

Server proxy

The browser has cross-origin restrictions, but the server does not have cross-origin issues. Therefore, the server can request the resources of the desired domain and then return them to the client.

Server proxy is omnipotent.

Document. domain to cross-subdomain

If the primary domain name is the same, but the subdomain name is different, you can use document. domain for cross-Origin
This method is very suitable for IFRAME cross-origin scenarios. Let's look at the example.
For example, the address of page a isa.yourhost.comPage B isb.yourhost.com.
In this way, you can setdocument.domain = yourhost.comTo implement cross-origin.
Then, you can get the window object of IFRAME through parent or window ['iframename.

Use window. Name for cross-Origin

Window. Name cross-origin is also restricted by the same-origin policy. The SRC of the parent framework and child framework must point to the unified domain name. The advantage of window. Name is that the value of name still exists after being loaded on different pages (or different domain names), unless you change it. The supported length is 2 MB.

The Code is as follows:

// Code of page a <SCRIPT type = "text/JavaScript"> IFRAME = document. createelement ('iframe'); IFRAME. style. display = 'none'; var state = 0; IFRAME. onload = function () {If (State = 1) {var DATA = IFRAME. contentWindow. name; console. log (data); iframe.content+doc ument. write (''); IFRAME. contentWindow. close (); document. body. removechild (IFRAME);} else if (State = 0) {state = 1; IFRAME. contentWindow. location = 'HTTP: // m.zhuanzhuan.58.com: 8887/B .html ';}}; document. body. appendchild (IFRAME); </SCRIPT>
// Page B code <SCRIPT type = "text/JavaScript"> window. Name = "hello"; </SCRIPT>
Window. Location. Hash cross-Origin

The location. Hash method is cross-origin. The sub-framework has the hash value to modify the SRC of the parent framework. Data is transmitted through this attribute and the hash value is changed. The page will not be refreshed. However, the number of bytes of transmitted data is limited.

Note: The Parent-Child Framework is restricted by the same-origin policy.

The Code is as follows:

// Code of page a <SCRIPT type = "text/JavaScript"> IFRAME = document. createelement ('iframe'); IFRAME. style. display = 'none'; var state = 0; IFRAME. onload = function () {If (State = 1) {var DATA = Window. location. hash; console. log (data); iframe.content+doc ument. write (''); IFRAME. contentWindow. close (); document. body. removechild (IFRAME);} else if (State = 0) {state = 1; IFRAME. contentWindow. location = 'HTTP: // m.zhuanzhuan.58.com: 8887/B .html ';}}; document. body. appendchild (IFRAME); </SCRIPT> // B page Code <SCRIPT type = "text/JavaScript"> parent. location. hash = "world"; </SCRIPT>
Window. Top

The window. Top method can access the top-level window objects and obtain the properties and methods of the top-level window objects. In this way, the framework can operate on the interaction of the parent page. Window. parent can get the window object of the parent framework.

The Code is as follows:

// A page Code <SCRIPT type = "text/JavaScript"> function FUNA () {console. log ("method of page a");} IFRAME = document. createelement ('iframe'); IFRAME. style. display = 'none'; IFRAME. src = 'HTTP: // m.zhuanzhuan.58.com: 8887/B .html '; document. body. appendchild (IFRAME); </SCRIPT> // code of page B <SCRIPT type = "text/JavaScript"> console. log (window. top. FUNA (); function funb () {console. log ("B PAGE method");} IFRAME = document. createelement ('iframe'); IFRAME. style. display = 'none'; IFRAME. src = 'HTTP: // m.zhuanzhuan.58.com: 8887/c.html '; document. body. appendchild (IFRAME); </SCRIPT> // code of the C page <SCRIPT type = "text/JavaScript"> console. log (window. parent. funb (); </SCRIPT>
Use postmessage to implement inter-page communication

In addition to transmitting information between the client and the server, there are also the following problems:

  • Page and new window data interaction.
  • Data Interaction between multiple windows.
  • Information Transmission Between the page and the nested IFRAME.

Window. postmessage is an HTML5 API that allows cross-origin message sending between two windows. This should be a general method for Dom cross-origin. For details, refer to MDN.

Supplement: there are still some methods, such as window. name and location. Hash. It is very suitable for cross-origin of IFRAME, but IFRAME is rarely used, so these methods are somewhat outdated.

These are my understanding of cross-origin. In actual situations, we can use common methods such as CORS and jsonp. However, in some unconventional situations, we still need to know more options.

Analysis of cross-origin requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.