On March 18, 2020, “One question of the Day series 🚀” by Wang Ergou blog: Dig gold, think not, Zhihu, Jane book, CSDN like again, form a habit, one question of the day series will be updated all the time, your support is the biggest motivation for me to continue to share 😘

The same-origin policy

Before we talk about cross domains, the first concept to understand is the same origin policy.

What is a source?

Source = Protocol + domain name + port number.

If the protocol, domain name, and port number of two urls are the same, the two urls are of the same origin.

We can get the current source via window.origin or location.origin.

https://wang.com
https://ergou.com
// Different source, different domain name (remember: the same name is only the same)

http://wang.com/index.html
http://wang.com/server.php
/ / the sameLocalhost call127.01. 
/ / different source
Copy the code

What is the same origin policy?

The same origin policy means that pages from different sources cannot access each other’s data.

If JS is running in source A, it can only obtain data from source A, not source B, that is, cross-domain is not allowed.

If wang.com/index.html references ergou.com/1.js, then 1.js runs in the source wang.com

Note that this has nothing to do with ergou.com, although 1.js was downloaded from it.

So 1.js can only get wang.com data, that’s what the browser does, and that’s what the browser is designed to do.

Why is there a same-origin policy?

The same origin policy is used to protect user privacy.

In the case of wechat, the source is https://user.weixin.com, assuming that the current user is logged in and the AJAX request /friends.json can get the user’s friends list.

Hackers to this time, he put the https://user-winxin.com to share with you, in fact it is a phishing site, you open this web page, the page also request your buddy list https://user.weixin.com/friends.json.

Excuse me, this time is your friend list stolen by hackers?

Root of the problem

The root cause of this problem is the inability to distinguish the sender.

There is almost no difference between the JS in wechat and the hacker’s JS sent to the request (referer difference)

But if the backend developer doesn’t check the referer, there’s no difference at all.

So, without the same origin policy, any page can steal the data in wechat, or even the balance in Alipay.

Security principle

Some friends may ask, since the referer is different, why not check the referer?

Safety principle: The strength of a safety chain is only as strong as its weakest link.

In the meantime, what if the backend developer of this site is an idiot?

So browsers should be proactive in preventing such data theft.

In short, to protect users’ privacy, browsers have strict same-origin policies.

If the browser does not limit cross-domain, there must be a bug in the browser.

Cross domain

What is cross-domain?

Cross-domain is when the browser tries to execute scripts from other sites. However, due to the same origin policy, we cannot achieve cross-domain.

A couple of questions about cross-domains

whya.wang.comaccesswang.comIt’s cross-domain, right?

Because there have been different companies sharing domain names throughout history, a.wang.com and wang.com are not necessarily the same site, and the browser has been careful to assume that these are different sources.

Why do different ports count as cross-domain?

For the same reason, one port one company is not uncommon.

Remember: a security chain is only as strong as its weakest link, and all security-related issues should be treated with caution.

Why two websitesIPIt’s also cross-domain, right?

For the same reason, IP can also be shared.

Why is it cross-domainCSS,JSAnd pictures and so on?

The same origin policy restricts data access. We refer to CSS, JS, and images without knowing what they are. We are just referring to them.

CORS cross-domain

What is CORS?

The full name of CORS is cross-origin Resource Sharing. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.

How to understand CORS?

If I own both wang.com and Ergou.com, and I just want wang.com to access ergou.com’s data, what should I do?

Just write ergou.com in the response header to make it accessible. That’s CORS.

The key to CORS communication is the server. As long as the server implements the CORS interface, cross-source communication is possible.

Two kinds of requests

CORS is divided into two types of requests across domains, one is simple request and the other is complex request.

A simple request

A simple request is one that meets the following criteria:

  • Request mode:HEAD,POSTorGET
  • The HTTP header does not exceed the following fields:Accept,Accept-LanguageContent-Language,Last-Event-ID,Content-Type(Limited to three values:application/x-www-form-urlencoded,multipart/form-data,text/plain)

A simple request is implemented by adding an Origin field to the header:

GET /cors HTTP/1.1
Origin: http://wang.com
Host: api.ergou.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0.Copy the code

Origin indicates the source of the request. The server determines whether to accept the request based on the Origin value.

If the source represented by Origin is not accepted by the server, the browser will automatically throw an error if it finds no access-Control-Allow-Origin field in the header of the response.

Note: This error is not recognized by the status code, which is also a disadvantage of implementing cross-domain requests through CORS.

If the source represented by Origin is accepted by the server, the server returns the following response:

Access-Control-Allow-Origin: http://api.ergou.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf- 8 -
Copy the code
  • Access-Control-Allow-Origin: This field is required. Its value is either when requestedOriginThe value of the field, or one*To accept requests from any domain name
  • Access-Control-Allow-Credentials: This field is optional. Its value is a Boolean value indicating whether sending is allowedCookie. By default,CookieIs not included in theCORSIn request. Set totrue, that is, the server is explicitly licensed,CookieIt can be included in the request and sent to the server. This value isCan only be set totrueIf the server does not send the browserCookie“, delete the field. (Note: If you are sendingcookie, not only do the above Settings, but also inAJAXSettings on requestwithCredentialsAttributes)
  • Access-Control-Expose-Headers: This field is optional.CORSThe request,XMLHttpRequestThe object’sgetResponseHeader()The method only gets six basic fields:Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma. If you want to get the other fields, you have to be inAccess-Control-Expose-HeadersSpecify inside.

Complex request

The so-called complex request, that is, the request that does not meet the above conditions is complex request.

For example, the request method is PUT or DELETE, or the content-Type field is application/ JSON.

Complex requests start with a precheck request from the Option method to know whether the server allows cross-domain requests.

var url = 'http://api.wang.com/cors';
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader('X-Custom-Header'.'value');
xhr.send();
Copy the code

The above request is a complex request, and when the browser discovers that it is a complex request, it automatically issues a precheck request asking the server whether to allow the request.

After receiving the precheck Request, the server checks the Origin, access-Control-request-method, and access-Control-request-headers fields and confirms that cross-source requests are allowed before responding to them.

Access-Control-Allow-Origin: http://api.wang.com
Content-Type: text/html; charset=utf- 8 -
Copy the code

Problems with CORS

Ie8/9 is not supported. If you want to use CORS across domains in IE8/9, you need to use XDomainRequest objects to support CORS.

The json cross-domain

What is JSONP?

When we cross domains, because the current browser does not support CORS or because some conditions do not support CORS, we have to use a different way to cross domains, so we ask for a JS file, which will perform a callback that contains the data we need.


let script = document.createElement('script');

script.src = 'http://www.wang.cn/login?username=wang&callback=callback';

document.body.appendChild(script);

function callback(res) {
  console.log(res);
}

Copy the code

What is the name of the callback function?

The name of the callback is a random number that can be generated at random. We pass this name as a callback argument to the background, which returns the function to us and executes it

Cross-domain advantages of JSONP

  • Compatible withie
  • You can cross domain

JSONP cross-domain disadvantages

  • Because it isscriptTag, so unreadableajaxSo the exact state, it doesn’t know what the status code is, it doesn’t know what the response header is, it just knows success and failure.
  • Does not supportpost(because it isscriptTags, so only supportedgetRequest)

Tell yourself that even if you are tired, don’t forget to learn. There is no shortcut to success, only step by step. ‘!

If there is something wrong in the article, you are welcome to correct it.

Thank you ~ 💘