Deep understanding of cross domain issues

Deep understanding of cross domain issues

In this article, you will learn:

What is homology, what is cross domain, what is source, and how to cross domain

1. Software description

Demo using web Services:
django3.2 
python3.9
vue 2

2. Problem description

  1. What is cross domain CORS
  2. What is homology strategy
  3. How to implement cross domain

3. Problem solving

3.1 what is homology strategy

If you want to understand the cross domain, you must first understand what is the homology strategy. For example, if you want to understand the "jailbreak" of Apple mobile phone, you must first understand what is the ios operating system.
Understand the following nouns:

3.1.1 source: (Origin) refers to protocol, domain name and port.

Source is https://www.baidu.com:80

3.1.2 homology: if the protocol, port number and domain name in the address are the same, it belongs to homology

For example:

Different source 1: different port numbers
https://www.csdn.net:80
https://www.csdn.net:8080
 Different sources 2: different protocols
http://www.csdn.net:80
https://www.csdn.net:80
 Different sources 3: different domain names
http://www.csdn.net:80
https://aaa.csdn.net:80
 Homology: domain name/Port number/The agreements are the same, and the following index.html And index.php Different, this is just a different route, not affected.
http://www.csdn.net/index.html:80
https://aaa.csdn.net/index.php:80

3.1.3 what is homology strategy

Homology policy is a security function of the browser. Client scripts from different sources cannot read and write each other's resources without explicit authorization.
Therefore, when we do the front-end and back-end separation, we deploy the front-end on a.com and the back-end on b.com. It appears when we use js on a.com and ajax requests

  1. As shown in the figure, we find an interface from CSDN
  2. We use ajax to call the interface in one of our a.html
alert('Cross domain request alert Popup');
axios.get('https://bizapi.csdn.net/im-manage/v1.0/dispatch/do', {
	responseType: 'json'
})
.then(response => {
	console.log(response.data)
})
.catch(error => {
	console.log(error.response.data);
})

After clicking send request, you can see the prompt of CORS error.

Test one again

alert('Cross domain request alert Popup');
axios.get('https://adv.xinnet.com/jsonp/list?callback=jQuery1124003561040491544598_1643606327196&groupCodes%5B%5D=sydh-domain&groupCodes%5B%5D=sydh-cloud&groupCodes%5B%5D=sydh-site&groupCodes%5B%5D=sydh-virtualhost&groupCodes%5B%5D=sydh-mail&groupCodes%5B%5D=sy-operation&groupCodes%5B%5D=sy-cloudfloor&groupCodes%5B%5D=float&_=1643606327197', {
responseType: 'json'
})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error.response.data);
})

We opened it and checked it carefully. We found that the request was successful, but no result was returned

The above is cross domain testing. When we use other tools to test, there is no problem. For example, Postman can see that there is no problem

This is also the same origin policy. The same origin policy is a policy of the browser, which means that you must abide by the same origin rules when using the browser.
Well, if we don't comply, I'll just add the header origin header to ajax,

You can see the browser prompt, which roughly means unsafe settings:
axios-0.18.0.min.js:8 Refused to set unsafe header "Origin"

And automatically change it to the host domain name where our js is located, which is the domain name we currently deploy js.

So this is a strategy of the browser itself. Some students said that we don't need the browser. Of course, we can request it with postman.

3.2 what is cross domain

CORS is a W3C standard, whose full name is "cross origin resource sharing".
If you know that it is the same source as the above, you can request resources on other machines through the machine deploying js, which is cross domain.
Cross domain: scripts from different sources operate on objects under other sources.
such as

a.com Front end interface deployed on the machine
 Back end interface deployed in b.com On, use a.com Upper js Request for ajax To request b.com Resources on are cross domain

So the problem is, since the browser doesn't allow cross domain, how to realize cross domain?

  • Not restricted by the same origin policy:
  1. Redirection in the page, form submission, links in the page, such as a tag and script tag.
  • Careful students may have found that as we said before, we can ask for success even across domains. As shown in the figure above, a return of 200 indicates that we succeeded, but where the server failed to pass Origin, so there was no result returned, but the result returned was to make the browser report an error.
  • In fact, the browser supports CORS, which mainly depends on the server itself. CORS needs the support of both browser and server. At present, all browsers support this function, and some may need a new version of browsers, such as ie.
  • The whole CORS communication process is completed automatically by the browser without user participation. For developers, CORS communication is no different from the same source AJAX communication, and the code is exactly the same. Once the browser finds that AJAX requests cross the source, it will automatically add some additional header information. Sometimes there will be an additional request, but the user will not feel it.
  • Therefore, the key to realize CORS communication is the server. As long as the server implements the CORS interface, it can communicate across sources.
  1. How to implement cross domain
    Take django as an example
Step 1: install the plug-in
pip install django-cors-headers
 Step 2: Import
INSTALLED_APPS = [
	......
    'corsheaders',
	......
]
Import'corsheaders.middleware.CorsMiddleware',Put on SessionMiddleware Back and CommonMiddleware In front, it's best to put it directly on the top.
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
]
Annotation is unnecessary
# 1. If True, the whitelist will not be used and all sources will be accepted. The default is False
# CORS_ORIGIN_ALLOW_ALL = True	

# 2. CORS_ ALLOW_ Credits allows cookies to be carried across domains. The default value is False
CORS_ALLOW_CREDENTIALS = True
# 3. CORS_ORIGIN_WHITELIST specifies the ip or domain name that can access the back-end interface. Whitelist
CORS_ORIGIN_WHITELIST = (
    'http://api.xxx.com',
    'http://api.xxx.com:8001',
)
# 4. Allowable methods
# CORS_ALLOW_METHODS = ('DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW',)
# 5. Allowed request header
# CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
    'x-token',
)

After setting, you can access it

The above is a cross domain problem. If you need a deeper understanding, you can continue to read it.

3.3 principle of cross domain request

Next, let's look at the above request method, which can cross domains. We can see that there are two fields in our return header, which can be roughly analyzed through translation, that is, http://www.meiduo.site The server allows this Origin request, and his qualification certificate is correct. Officially, our www.meiduo.com Site is our front-end deployment.

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://www.meiduo.site


There are two types of cross domain requests: one is simple request and the other is non simple request

  1. Simple request means that the browser sends CORS request directly
  2. It is not a simple request, that is, you need to send a pre check (OPTIONS request) before sending a request (PUT/DELETE, etc.)
    So what are simple requests and complex requests?

Function overview

Official words: the cross source resource sharing standard adds a set of HTTP header fields, allowing the server to declare which source stations have access to which resources through the browser. In addition, the specification requires that for those HTTP request methods that may have side effects on server data (especially HTTP requests other than GET, or POST requests with some MIME types), the browser must first use the OPTIONS method to initiate a preflight request to know whether the server allows the cross source request. After the server confirms that it is allowed, it initiates the actual HTTP request. In the return of the pre check request, the server can also notify the client whether it needs to carry identity credentials (including Cookies and HTTP authentication related data).
Human voice: in order to prevent side effects on the server, when it is necessary to send a request again, send a pre check request (OPTIONS), especially for requests other than GET. It is necessary to obtain whether the browser agrees to the request through the pre check request of OPTIONS.

The failure of CORS request will cause errors, but for security, it is impossible to know exactly what went wrong at the JavaScript code level. You can only check the browser console to know exactly where the error occurred.

However, simple requests do not trigger pre checks

What is a simple request

Requests that do not trigger pre check are simple requests
A request can be considered a "simple request" if all of the following conditions are met:

1. Use one of the following methods:
	GET
	HEAD
	POST
2. In addition to the header fields automatically set by the user agent (for example Connection,User-Agent)And in Fetch Other headers defined in the specification as disabling header names, and the fields allowed to be manually set are Fetch Specification defined pair CORS A collection of secure header fields. The set is:
Accept
Accept-Language
Content-Language
Content-Type (Need to pay attention to additional restrictions)
Content-Type The value of is limited to one of the following three:
	text/plain
	multipart/form-data
	application/x-www-form-urlencoded
3, Any of the requests XMLHttpRequest None of the objects have registered any event listeners; XMLHttpRequest Object can use XMLHttpRequest.upload Property access.
4. Not used in request ReadableStream Object.

HTTP response header

1. Access-Control-Allow-Origin Specify source
# The value of the origin parameter specifies the foreign domain URI that allows access to the resource. For requests that do not need to carry identity credentials, the server can specify the value of this field as a wildcard [*], indicating that requests from all domains are allowed.
Access-Control-Allow-Origin:*
# for example
Access-Control-Allow-Origin: https://mozilla.org
Vary: Origin
 If the server specifies a specific domain name instead of“*",Then respond to the in the header Vary The value of the field must contain Origin. This will tell the client that the server returns different content to different origin sites.
2. Access-Control-Expose-Headers Specify response header
 When accessing across sources, XMLHttpRequest Object getResponseHeader() The method can only get some basic response headers, Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,If you want to access other headers, you need the server to set this response header
3. Access-Control-Max-Age Specify the cache time of pre check and how long it will be before the pre check again. The unit of second is that the pre check is not initiated within the cache time.
Access-Control-Max-Age The header is specified preflight For how long the result of the request can be cached, please refer to the above mentioned in this article preflight example.
Access-Control-Max-Age: <delta-seconds>
delta-seconds Parameter representation preflight The number of seconds the result of the pre inspection request is valid.
4. Access-Control-Allow-Credentials Allow to carry vouchers. Voucher is Cookie ,Authorization header or TLS Client certificate.
Specifies the name of the browser credentials Set to true Allow browser to read when response Content of the. When used in pairs preflight When pre detecting the response of the request, it specifies whether the actual request can be used credentials. Please note: simple GET The request will not be pre checked; If the response to such a request does not contain this field, the response will be ignored and the browser will not return the corresponding content to the web page.
5. Access-Control-Allow-Methods The header field is used to respond to the pre inspection request. It indicates the allowed usage of the actual request HTTP method.
6. Access-Control-Allow-Headers The header field is used to respond to the pre inspection request. It indicates the header field allowed in the actual request.

reference

1. Cross domain resource sharing CORS
2. django-cors-headers

Keywords: Javascript Front-end Ajax http

Added by jeephp on Tue, 01 Feb 2022 10:31:29 +0200