15 beautiful moving pictures to fully explain CORS

Time:2021-3-4

15 beautiful moving pictures to fully explain CORS

preface:

This article is translated fromLydia HallieIt was written by my little sister✋🏼🔥 CS Visualized: CORSShe used a lot of moving pictures to explain the concept of CORS, but no one has translated this article in China, so I translated this article and corrected some mistakes in the understanding of the original text, hoping to help you.

I think the translation is good. I mustLike itThank you, it’s really important to me!

Note: all the moving pictures in the original text arekeynotemake

In front-end development, we often use data from other sites. Before the front end displays the data, it must make a request to the server to get the data.

Suppose we are visitinghttps://api.mywebsite.comThis site, click the button tohttps://api.mywebsite.com/usersSend a request to get some user information on the website:

15 beautiful moving pictures to fully explain CORS

⚠️ Here is a mistake made by the original authorhttps://api.mywebsite.comMistakenly written ashttps://www.mywebsite.comWell, there is also this mistake in the picture. Readers should be careful not to be misled

From the result, the performance is very perfect. We send the request to the server, the server returns the JSON data we need, and the front end also renders the result normally.

Now let’s try another website. usehttps://www.anotherwebsite.comThis website provideshttps://api.website.com/usersSend request:

The problem came, we asked for the same interface website, but this time the browser threw us an error.

CORS error was just thrown by the browser. Let’s analyze why this error occurs and what the exact meaning of this error is.

1. Homology strategy

When the browser network requests, there is aHomologous strategyThe mechanism of innovation. That is, by default, web applications using API can only request HTTP resources from the same domain where the application is loaded.

for instance,https://www.mywebsite.comrequesthttps://www.mywebsite.com/pageThere is no problem at all. But when resources are located in different locationsagreementSubdomainorportThis request is cross domain.

15 beautiful moving pictures to fully explain CORS

At present, the homology strategy will restrict three kinds of behaviors

  • Restricted access to cookies, localstorage and indexdb
  • Unable to manipulate cross domain DOM (common in iframe)
  • XHR and fetch requests initiated by JavaScript are limited

So why is there a homologous strategy?

Let’s make a hypothesis. If there is no homologous strategy, you accidentally click on the link of a health article sent to you by Aunt Qi on wechat. In fact, this webpage is a phishing website. After visiting the link, you will be redirected to an attack website embedded with iframe, which will automatically load the bank website and log in to your account through cookies.

After successful login, the phishing website can also control the dom of iframe and transfer the money from your card through a series of operations.

15 beautiful moving pictures to fully explain CORS

This is a very serious security loophole. We don’t want our content on the Internet to be accessed casually, let alone this website involving money.

The same origin policy can help us solve this security problem, which ensures that we can only access the resources of the same site.

15 beautiful moving pictures to fully explain CORS

under these circumstances,https://www.evilwebsite.comTry cross site accesshttps://www.bank.comThe same source policy will prevent this operation, and the phishing website will not be able to access the data of the bank website.

What is the relationship between homology strategy and CORS?

2. Browser CORS

Browser restrictions for security reasonsInitiate from within scriptCross domain HTTP request for. XHR and fetch, for example, follow the same origin strategy. This means that web applications using the API can only request HTTP resources from the same domain where the application is loaded.

15 beautiful moving pictures to fully explain CORS

In daily business development, we often visit cross domain resources. In order to request cross domain resources safely, the browser uses a mechanism called CORS.

What is the full name of CORSCross-Origin Resource Sharing, i.eCross domain resource sharing. Although browsers prohibit us from accessing cross domain resources by default, we can use CORSrelaxThis kind of restriction can access cross domain resources on the premise of ensuring security.

The browser can use CORS mechanism to release cross domain access conforming to the specification and prevent cross domain access not conforming to the specification. How to do it inside the browser? Let’s analyze it.

After a web application makes a cross domain request, the browser willautomaticAdd an additional request header field to our HTTP header:OriginOriginMarked the site source of the request:

GET https://api.website.com/users HTTP/1/1
Origin:  https://www.mywebsite.com //  < - browser added

15 beautiful moving pictures to fully explain CORS

In order to allow the browser to access cross domain resources, the response returned by the server needs to add some response header fields, which willExplicit expressionWhether this server allows this cross domain request.

3. Server CORS

As a server developer, we can add additional response header fields to the HTTP responseAccess-Control-*To indicate whether cross domain requests are allowed. According to these CORS response header fields, the browser can allow some cross source responses limited by the same origin policy.

Although there areSeveral CORS response header fields, but one field isBijiaYes, that’s itAccess-Control-Allow-Origin. The value of this header field specifies which sites are allowed to access resources across domains.

one ️⃣ If we have the development permission of the server, we can give thehttps://www.mywebsite.comAdd access: add the domain to theAccess-Control-Allow-OriginIn the middle.

15 beautiful moving pictures to fully explain CORS

The response header field is now added to the response header sent back by the server to the client. After this field is added, if wehttps://www.mywebsite.comWhen sending cross domain requests, the same origin policy will no longer be restrictedhttps://api.mywebsite.comResources returned by the site.

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://www.mywebsite.com
Date: Fri, 11 Oct 2019 15:47 GM
Content-Length: 29
Content-Type: application/json
Server: Apache

{user: [{...}]}

15 beautiful moving pictures to fully explain CORS

2. After receiving the response from the server, the CORS mechanism in the browser will checkAccess-Control-Allow-OriginWhether the value of is equal to the value in the requestOriginThe value of.

In this case, theOriginyeshttps://www.mywebsite.comThis is the same as in responseAccess-Control-Allow-OriginThe value of is the same:

three ️⃣ The browser passed the verification, and the front end successfully received the cross domain resources.

Well, when we’re trying to get away from one that’s not thereAccess-Control-Allow-OriginWhat happens when the web sites listed in cross domain access these resources?

As shown in the figure above, fromhttps://www.anotherwebsite.comCross domain accesshttps://api.mywebsite.comResources. The browser throws a CORS error. After the above explanation, we can read the error message:

The 'Access-Control-Allow-Origin' header has a value
 'https://www.mywebsite.com' that is not equal 
to the supplied origin. 

under these circumstances,OriginThe value of ishttps://www.anotherwebsite.com. However, the server isAccess-Control-Allow-OriginThe site is not marked in the response header field. The browser CORS mechanism blocks the response. We can’t get the response data in our code.

CORS also allows us to add wildcards*As an allowed foreign domain, this means that the resource can be usedarbitrarilyForeign domain access, so pay attention to this special case


Access-Control-Allow-OriginIt is one of the header fields provided by CORS mechanism. Server developers can also extend the server’s CORS policy through other header fields to allow / disallow certain requests.

Another common response header field isAccess-Control-Allow-Methods. It indicates the HTTP methods allowed for cross domain requests.

15 beautiful moving pictures to fully explain CORS

In the case above, onlyGETPOSTorPUTMethod is allowed to access resources across domains. Other HTTP methods, such asPATCHandDELETEWill be stopped.

If you want to know what the other CORS response header fields are and what they are used for, you canView this list

Speaking ofPUTPATCHandDELETECORS handles these HTTP methods differently. These non simple requests trigger CORS pre check requests.

4. Pre inspection request

CORS has two types of requests: one isSimple requestOne isPreflight request. Whether a cross domain request is simple or pre checked depends on some request headers.

When the request isGETorPOSTMethod without any custom header fields, it is generally a simple request. Any other request, such asPUTPATCHorDELETEMethod, a preview will be generated.

If you want to know what requirements a request must meet to become a simple request, you can look at the MDNSimple requestdependentfile

So much has been saidPre inspection requestWhat does that mean? Now let’s discuss it.


1. Before sending the actual request, the client will use theOPTIONSMethod to initiate a pre check request. TheAccess-Control-Request-* Contains information about the actual request we are going to process:

OPTIONS https://api.mywebsite.com/user/1 HTTP/1.1
Origin: https://www.mywebsite.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type

15 beautiful moving pictures to fully explain CORS

two ️⃣ After receiving the pre check request, the server will return an HTTP response without body, which marks the HTTP method and HTTP header field allowed by the server

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://www.mywebsite.com
Access-Control-Request-Method: GET POST PUT
Access-Control-Request-Headers: Content-Type

three ️⃣ The browser receives a pre check response and checks whether the actual request should be allowed to be sent.

15 beautiful moving pictures to fully explain CORS

⚠️ : the pre check response in the figure above is missingAccess-Control-Allow-Headers: Content-Type

four ️⃣ If the pre check response passes, the browser will send the actual request to the server, and then the server will return the resources we need.

15 beautiful moving pictures to fully explain CORS

If the pre check response fails, CORS will block cross domain access, and the actual request will never be sent. Pre check requests are a good way to prevent us from accessing or modifying resources on servers that do not have CORS policy enabled.

In order to reduce the number of network round trips, we can add theAccess-Control-Max-AgeHeader field to cache the preview response. Instead of sending new pre check requests, browsers can use caching.

5. Certification

An interesting feature of XHR or fetch and CORS is that we can base onCookiesAnd HTTP authentication information. In general, for cross domain XHR or fetch requests, the browsercan’tSend ID information.

Although CORS does not send identity credentials by default, we can addAccess-Control-Allow-CredentialsCORS response header to change it.

If we want to include cookies and other authorization information in cross domain requests, we need to do the following:

  • XHR requestwithCredentialsField set totrue
  • Fetch requestcredentialsSet toinclude
  • Server handleAccess-Control-Allow-Credentials: trueAdd to response header
//Browser fetch request
fetch('https://api.mywebsite,com.users', {
  credentials: "include"
})

//Browser XHR request
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;

//Server add authentication field
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true

15 beautiful moving pictures to fully explain CORS

After doing the above work well, we can include the identity certificate information in the cross domain request.

6. Summary

CORS error is a headache for front-end development to a certain extent, but after following its relevant regulations, it allows us to make secure cross domain requests in the browser.

There are many knowledge points about homology strategy and CORS. This article only talks about some key knowledge points. If you want to learn the relevant knowledge of CORS comprehensively, I recommend you to consultMDN documentandW3C specificationThis first-hand knowledge is the most accurate.

recommend

That’s the end of this article. If you think it’s good, you must praise and encourage me. I wish you progress in your study and smooth work!

If you want to learn more about non note taking HTTP, you can take a look at my old article:

Finally, I recommend my personal number:Egg Lab, will update some front-end technology and graphics related articles, original, welcome your attention.