preface

Cross-domain problem is a front-end development around the past problem, often make developers very headache, let’s talk about the origin of cross-domain problem, and how to correctly solve the cross-domain problem!

What is cross-domain

First of all, why does cross-domain happen?

Before we answer that question, let’s look at two examples:

csrf

1. If I visit site A with A browser, site A stores some private information under the cookie of site A’s domain name

2. At this time, I visited site B with the browser. The script of site B obtained the information below site Acookie and forged an Ajax request to modify the user’s information, which was a very dangerous operation!

3. The whole process above is called -Cross-domain Request Forgery (CSRF), as shown in the figure below:

Cross-domain DOM access

1. Suppose I make a bank website (fake) and use iframe to link the real bank website to my own website

2. At this time, the bank user visited my bank website without knowing it, but entered his account and password in the real bank site

3. At this time, I accessed the DOM structure of the real website through my fake website and obtained the user’s account number and password, which was also very dangerous

From the above two examples, we know that if the browser does not have a cross-domain policy, there are many, many security problems (not limited to the above examples) that can have a large impact and unpredictable consequences!

Based on this, browser introduced by Netscape in 1995 proposed the same origin policy to restrict the mutual access of resources between different domains and improve the security of websites. It is this same origin policy that introduces the problem of cross-domain access by browsers.

So what is the same origin policy? Does it improve security? Let’s move on.

What is the same-origin policy

I keep saying homology, but what is homology? What does homology have to do with cross-domain?

The relationship between cross-domain and homology can be summed up in one sentence — the same-origin policy introduces cross-domain problems

So how do browsers define the same origin policy? It’s easy. Let’s start with the following picture:

As we all know, a URL address is basically composed of protocol, domain name, port and path. When defining homology, only the protocol, domain name and port are used. As the name implies, to judge whether a site or two sites are homology, we only need to see whether their protocol, domain name and port are the same. There is a simple exercise in the picture, you can see how well you have mastered it!

Through learning, we understand the same origin policy of the browser, which is the basic rule of the browser. It defines the resource exchange protocol between cross-domain sites, and stipulates which resources can and cannot be exchanged between cross-domain sites.

Now that we know about the same-origin policy, let’s take a look at what the same-origin policy does to restrict access to resources between sites:

The same origin policy states:

(1) Cookies, LocalStorage and IndexDB cannot be read between cross-domain sites.

(2) DOM cannot be obtained between cross-domain sites.

(3) Restrict AJAX requests between cross-domain sites.

By learning the same origin policy, we know that different sites (across domains, from different sources) cannot access cookies and DOM to each other, which solves the security problem we encountered at the beginning of this article. However, the cross-domain policy is also the most basic security policy. It cannot completely limit security issues such as CSRF, which needs to be noted.

The same origin policy is a security policy of the browser. It aims to improve the security of the browser, but it also brings cross-domain problems. Therefore, the same origin policy is a balance between the security and availability of the browser.

Cross domain example

Now that we know where cross-domains come from, let’s look at a cross-domain example in action:

Figure, we from the domain https://test.dev.com.cn:4010 access to the domain https://vg-config-pre.vmic.xyz, is the browser check out ajax cross-domain request, so an error! Complies with Rule 3 of the Same Origin policy!

Figure 2 and figure 3, we from the domain https://test.dev.com.cn:4010 access to the domain https://vg-config-pre.vmic.xyz, we look at this request, found the request and the difference between homologous ajax is that it sends a request, not carrying the cookie information! This is consistent with the first same-origin policy!

As for the same origin policy number two, we can easily imagine using the embedded IFrame example.

Cross domain policy

Browsers have introduced same-origin policies to improve security at the expense of usability. In order to improve the communication ability between different domains, the browser provides a cross-domain solution, that is, CORS — cross-domain policy!

Now, what is CORS

For CORS, it’s official: Cross-source resource sharing (CORS) (or, collocially, cross-domain resource sharing) is an HTTP header based mechanism that allows a server to identify other origins (domains, protocols and ports) besides its own, so that browsers can access and load those resources.

Cors is a cross-domain policy implemented by the browser through HTTP headers. The browser can specify which domains other than itself to allow access through the HTTP response header and return cross-domain information to the browser. The browser can carry its own identity information in the HTTP request header, so that the server can determine whether to allow it to cross domains.

Through studying the CORS rules, we learned two key things:

First, cross-domain policies are implemented by telling the browser whether to allow them through HTTP request headers and HTTP response headers

Second, the cross-domain policy is actually a question and answer policy. The browser asks the browser whether to allow cross-domain access through the HTTP request header, and the server tells the browser whether to allow cross-domain access through the HTTP response header

What requeset headers and Response Headers do cross-domain policies specify?

Header: Indicates the source domain name of the request. Header: indicates what headers are carried in the request. Method: Access-control-request-method: specifies which methods are allowed by the server to cross domain access-Control-request-headers: Access-control-allow-origin: Specifies which domains are allowed by the server. Access-control-max-age: 86400: For complex requests, the validity period of the precheck request is specified.Copy the code

You can see that there is a one-to-one correspondence between the request header and the response header. If the information carried by the request header fully conforms to the rules of the response header, the request can be accessed across the domain. Note that all the conditions are met!

This is the main content of cORS cross-domain policy. In addition to these, CORS also distinguishes HTTP requests into simple and complex requests based on some rules

Simple versus complex requests

The cross-domain flow of simple and complex requests is different, and complex requests have one more precheck request than simple requests. We can look at the following figure to see what a simple request is:

As you can see, requests that fully meet the above five criteria are called simple requests, and the rest are complex requests.

Simple request cross-domain process

What is the cross-domain flow of simple requests? The cross-domain request is sent directly to determine whether the cross-domain information carried in the request header complies with the cross-domain rule specified in the response header, as shown in the following figure. The source of the request is Origin: foo.example, and the response header access-Control-allow-Origin: * Specify that all domains can be accessed across domains, completing the entire process of cross-domain access.

Complex request cross-domain processes

A request that does not meet the above five criteria is called a complex request, and the following code sends an XML document using a POST request that contains a custom request header field (X-pingother: Pingpong). Also, the content-type of the request is Application/XML. Therefore, the cross-domain process of the request needs to initiate a “precheck request” first.

var invocation = new XMLHttpRequest(); var url = 'http://bar.other/resources/post-here/'; var body = '<? The XML version = "1.0"? ><person><name>Arun</name></person>'; function callOtherDomain(){ if(invocation) { invocation.open('POST', url, true); invocation.setRequestHeader('X-PINGOTHER', 'pingpong'); invocation.setRequestHeader('Content-Type', 'application/xml'); invocation.onreadystatechange = handler; invocation.send(body); }}Copy the code

Let’s take a look at the cross-domain process of complex requests. Complex requests will send a pre-check request with the request method of Options to determine whether the request header of the pre-check request meets the cross-domain rule of the server’s response header. If so, formal requests will be sent to complete the cross-domain process. As shown in the following figure, the source of the request is Origin: foo.example, and the response header access-Control-allow-origin: http://foo.example specifies that foo.example can be accessed across domains. After the browser receives a message that allows cross-domain access, it sends a formal request to complete the cross-domain access. Adding a precheck request policy for complex requests may be for security reasons.

Whether it is a complex request or a simple request, it is ultimately a matter of determining whether the request header and the cross-domain rules set by the response header are met! This also determines that the solution of cross-domain problems requires front-end and server cooperation.

Access-control-max-age = access-Control-max-age = access-Control-max-age If the value is set to 86400 in the response header, the validity period of the precheck request is 86400ms. If the value is set to 86400 in the response header, the validity period of the precheck request is 86400ms. If the value is set to 86400ms in the response header, the validity period of the precheck request is 86400ms.

That’s CORS!

To solve the cross domain

Now that we know about same-origin and cross-domain policies, let’s learn how to solve cross-domain problems!

There are two ways of thinking:

1. Configure on the server directly according to cross-domain requirements, and apply to test environment, pre-delivery environment and online environment

2. Use proxies to convert different domains into the same domain, mostly in development environments

Server configuration solutions to cross – domain problems, we do not say more, belong to the communication problem. Let’s look at how the front end itself can be accessed across domains by proxy.

Development environment – WebPack devServer

Convert ajax requests to the same domain name as the server site (eliminating cross-domain) directly using the proxy provided by WebPack, which is generally used in development environments:

devServer: {
    host: 'vg-config-dev.vmic.xyz',
    proxy: {
      '/api-v0': {
        target: 'https://vg-palace-test.vivo.com.cn',
        changeOrigin: true,
        secure: true,
        logLevel: 'debug'
      }
    }
  }
Copy the code

Suppose that the domain name of my local application is http://vg-config-dev.vmic.xyz:8080 and the server interface I want to access is https://vg-palace-test.vivo.com.cn/api-v0/getConfig?id=20. This is where cross-domain access occurs, proxying http://vg-config-dev.vmic.xyz:8080 to https://vg-palace-test.vivo.com.cn by proxying the /api-v0 rule, When I visit http://vg-config-dev.vmic.xyz:8080/api-v0/getConfig?id=20, Actually go to https://vg-palace-test.vivo.com.cn/api-v0/getConfig?id=20, http://vg-config-dev.vmic.xyz:8080/api-v0/getConfig?id=20 is the same as the domain name http://vg-config-dev.vmic.xyz:8080 of my site, avoiding cross-domain access and realizing normal interface access.

Development environment – Nginx

Nginx (pronounced “engine X”) provides load balancing and proxy services.

The software was created by и горь с ысоев and first publicly released in 2004, Russia.

On March 11, 2019, Nginx was acquired by F5 Networks for $670 million.

Russian developed products, bought by us dollars, can see science has no borders (joke)!!

Nginx can implement forward proxy (proxy client) and reverse proxy (proxy server), we all know VPN, we access foreign websites through VPN, is a practical example of forward proxy. We are using Nginx forward proxy function to solve cross-domain problems, the following to introduce the specific process of Nginx cross-domain implementation.

Niginx Server Download (MAC)

1. First download Homebrew, MAC software Download management tool

2. Use Homebrew to download nginx and run brew install nginx to download nginx

3. Download switchHost

Nginx – Forward proxy implementation across domains

Assume that the local project runs on http://10.15.51.236:8081 and the cross-domain policy of the back end is Access-Control-Allow-origin:.vivo.com.cn

We use nginx to delegate the local project http://10.15.51.236:8081 to 10.15.51.236:80 as follows:

Edit nginx configuration, command line executive vim/usr/local/etc/nginx/nginx. Conf, then edit text:

Then start the nginx proxy: execute the nginx command from the command line

Enable the Switchhost agent and proxy http://game-bbs.vivo.com.cn to http://10.15.51.236

We know that when we access the domain name directly without the port number, we access the default port 80, so when we access http://game-bbs.vivo.com.cn, the switchHost proxy actually accesses http://10.15.51.236, That is, access http://10.15.51.236:80 and, through the nginx agent, access http://10.15.51.236:8081.

At this time, the domain name of our local project is changed to http://game-bbs.vivo.com.cn, which is in line with our predefined interface cross-domain policy. Vivo.com.cn, cross-domain is successfully implemented!

Nginx – Reverse proxy implementation across domains

Proxy server: This scheme is generally used in test environment, pre-release environment and formal environment.

The principle of reverse proxy is very simple. Nginx takes the place of the server to allow cross-domain domain, headers, and method requests.

conclusion

Cross-domain is a problem caused by the same origin policy of the browser, and the browser provides a cross-domain solution!

Cross-domain issues are a front-end issue (front-end introduction), but solving cross-domain issues requires server or O&M cooperation!

reference

1, developer.mozilla.org/zh-CN/docs/…

2, developer.mozilla.org/zh-CN/docs/…

3, www.ruanyifeng.com/blog/2016/0…