Cross domain problem whether front-end or back-end will be a problem to face, this article through several specific examples to explain the same origin policy and CORS, more front-end content welcome to my Blog: www.godrry.com/

Browser Same-origin Policy

The same origin policy is a security policy of the browser. All browsers now implement this policy, which was introduced by NetScape in 1995.

define

The same protocol, domain name, and port are the same. If any of the three are different, they are restricted by the same origin policy, including but not limited to Cookie reading.

Take a chestnut: this web site, http://www.godrry.com/archives/why-cant-you-admit-youre-wrong.html

  • Agreement ishttp://
  • Domain name iswww.godrry.com
  • The port is80Of course, 80 is the default port and can be omitted

It may have the following homology cases:

http://www.godrry.com/category/life/ = > [the same] http://my.godrry.com/category/life/ = > [domain different] https://www.godrry.com/category/life/ = > [agreement] different http://www.godrry.com:6670/category/life/ = > [port] differentCopy the code

meaning

The browser’s same-origin policy is a form of protection. It must restrict the contact between non-same-origin sites to ensure that they work properly and do not disturb each other. For example, when we log in to website A, the login information is stored in cookies, and then we open website B. If the relationship between A and B is not restricted, THEN B may read the cookies in WEBSITE A, and the user’s information security will be threatened.

limit

If not homologous, the following restrictions apply

  • Unable to getDOM
  • Unable to readCookie,LocalStorage,IndexDB
  • Unable to sendAjaxrequest

Relatively speaking, these restrictions ensure the information security of users and restrict the behavior between websites, but sometimes they may also bring some inconvenience. So there are ways to get around the same-origin policy. Let’s talk about how to send Ajax requests without being restricted by the same origin policy.


Cross-domain resource sharing CORS

CORS: Cross-Origin Resource Sharing, a standard developed by W3C, is used to allow browsers to send XML requests to cross-source servers, enriching the application scenarios of Ajax. This is a modern browser policy that has relaxed the same origin policy.

participants

Browsers and servers are major participants in CORS. Browsers need to support CORS to make requests and receive responses, while cross-source servers need to implement the CORS interface. At present, all browsers support CORS (IE 10 or more). When the browser discovers that the request belongs to a cross-source request, it automatically adds some attached request headers and sometimes makes a pre-request. Cross-source servers require configuration to implement the CORS interface.

In both cases, configuration across source servers is key.

There are two types of CORS requests

CORS requests are classified into simple requests and non-simple requests. Browsers handle CORS requests differently.

A simple request

A request is simple if it meets the following two criteria (or non-simple if it does not) :

  • Request methods are limited to:HEAD.GET.POST
  • HTTP headers are limited to:Accept.Accept-Language.Content-Language.Last-Event-ID.Content-Type
  • whileContent-TypeLimited to:application/x-www-form-urlencoded,multipart/form-data,text/plain

Last-event-id header that the browser sends to help the server rebuild the connection.

When the browser sends a CORS request, if it finds that it is a simple cross-source request, it adds the Origin field in the request header to tell the server where the request is from. The value includes the protocol, domain name, and port of the request source. The server determines whether to approve the request based on Origin in the request header.

Permission Request:

The server will add in the response header

Access-Control-Allow-Origin: http://www.godrry.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: Godrry
Copy the code
  • Access-control-allow-origin specifies the domain name that allows cross-source requests. Generally, it has two values: the requested domain name, and * indicates that all domain names are allowed to make cross-source requests. “Choice”

  • Access-control-allow-credentials Specifies whether the response content is exposed to the request source. The response content can be cookies, Authorization headers or TLS Client certificates. If you set it to true, it is allowed, if you don’t set it to false, but it is not allowed to set false, so if you want it to be true, If not, you can ignore this field. [optional]

    In addition, CORS requests do not send cookies and HTTP authentication information by default, so if you want to carry this information with XML requests, you need to configure the following attributes

    let xhr = new XMLHttpRequest()
    xhr.withCredentials = true
    Copy the code

    If you want to send cookies, the access-Control-allow-origin in the server response header cannot be set to *, and the domain name with the same Origin as the request source must be clearly specified. In this case, the Cookie information is still restricted by the same Origin policy. Only the Cookie set by the server domain name will be sent along with the request. In addition, the Document. Cookie cannot read the Cookie information

  • Access-control-expose-headers specifies whether to Expose other response Headers to the request source. Defaults include cache-Control, Content-language, Content-Type, Expires, last-Modified, and Pragma, all of which are available through XML’s getResponseHeader() method, But if you need to expose other response fields to the request source, you need to specify which response headers to use. Set access-Control-expose-headers: Godrry as above, and the Godrry response header will get its value via getResponseHeader(‘Godrry’). [optional]

Disallowed request:

The server uses the Origin field in the request header to determine that the request is not allowed. The server will also respond to the request, but will not contain the Access-Control-Allow-Origin field. When the browser receives the response and does not find the response header, it will throw an error. XMLHttpRequest’s onError event caught an error. Note that the Status Code returned by the server may be 200, so it is impossible to determine whether the request was successful.

Non-simple request

If the browser finds that the request is not simple, the non-simple request contains two requests: the precheck request and the formal request. Of course, if the precheck request does not pass, no actual request is made.

Precheck Request (Preflight)

The browser sends a pre-check request to the server to ask if the request is approved before the formal request. The permission includes Origin, request mode (verb), and request header.

Next we send a non-simple request to the server example.godrry.com with the request verb PUT and set a custom header:

let xhr = new XMLHttpRequest()
xhr.open('PUT'.'http://example.godrry.com')
xhr.setRequestHeader('My-Custom-Header'.'bingo')
xhr.send()
Copy the code

The browser sends a precheck request (with the request verb OPTION), sets the following request header to inform the server of the formal request with the request verb and additional header information fields, etc.

Access-Control-Request-Headers: content-type,my-custom-header
Access-Control-Request-Method: PUT
Origin: http://demo.godrry.com.Copy the code

If the server approves the request, it will have the following response header:

access-control-allow-headers: content-type,my-custom-header
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-origin: *
Copy the code
  • access-control-allow-originSpecifies who the server permits to perform CORS, or can be set to*
  • access-control-allow-methodsRepresents how the server requests permission for CORS
  • access-control-allow-headersRepresents all headers for the server license CORS

The browser then sends a formal request, which, like a simple request, adds Origin to the request header and always carries Access-Control-Allow-Origin in the server’s response header. If the precheck is performed again, the server can set the access-Control-max-age field to set the validity period of the precheck request if you want to omit the precheck step after the precheck passes.

If the server does not approve the request and there is no relevant CORS field in the response header, the browser will throw an error caught by XML’s onError event. The browser console also prints the error.