Cross-domain resource sharing CORS detailed

Source: Internet
Author: User
Tags http authentication send cookies

Cors is a universal standard, with the name "cross-domain resource sharing" (cross-origin resource sharing).

It allows the browser to make requests to cross-origin servers, XMLHttpRequest overcoming the limitation that Ajax can only use the same origin.

This article describes the internal mechanisms of cors in detail.

(Photo description: An oasis park in Al Ain, UAE)

First, Introduction

Cors requires both browser and server support. Currently, all browsers support this feature, IE browser cannot be less than IE10.

The entire cors communication process is done automatically by the browser and does not require user involvement. For developers, Cors Communication is no different from the same-Origin Ajax communication, and the code is exactly the same. Once the browser discovers that the AJAX request crosses the source, it automatically adds some additional header information, sometimes with an additional request, but the user does not feel it.

Therefore, the key to achieving cors communication is the server. As long as the server implements the Cors interface, it can communicate across the source.

II. two types of requests

The browser divides the Cors requests into two categories: simple request and non-simple (Not-so-simple request).

As long as the following two conditions are met, it is a simple request.

(1) The request method is one of the following three methods:

    • HEAD
    • GET
    • POST

(2) HTTP header information does not exceed the following types of fields:

    • Accept
    • Accept-language
    • Content-language
    • Last-event-id
    • Content-type: Limited to three values application/x-www-form-urlencoded , multipart/form-datatext/plain

It is a non-simple request that does not satisfy the above two conditions at the same time.

The browser does not handle these two requests in the same way.

Three, simple request 3.1 basic process

For simple requests, the browser makes a cors request directly. Specifically, in the header information, add a Origin field.

Here is an example where the browser discovers that the cross-origin Ajax request is a simple request and automatically adds a field to the header information Origin .

Get/cors http/1.1Origin:Http://api.bob.comHost:Api.alice.comAccept-language:En-USConnection:Keep-aliveuser-agent:mozilla/5.0 ...

In the header information above, the Origin field is used to indicate which source (protocol + domain + port) The request came from. Based on this value, the server decides whether to agree to this request.

If Origin the specified source is not within the scope of the license, the server returns a normal HTTP response. The browser found that the header information for this response did not contain a Access-Control-Allow-Origin field (see below), and knew that something was wrong, and then threw an error that was XMLHttpRequest captured by the onerror callback function. Note that this error cannot be identified by the status code because the status code of the HTTP response is likely to be 200.

If the Origin specified domain name is within the permitted range, the response returned by the server will have a few more header information fields.

Access-control-allow-origin:Http://api.bob.comaccess-control-allow-credentials:Trueaccess-control-expose-headers:FooBarContent-type:text/html; Charset=utf-8

Among the header information above, there are three fields related to cors requests, all starting with the first Access-Control- .

(1) Access-control-allow-origin

This field is required. Its value is either the value of the field at the time of the request Origin , or one * that represents the request to accept any domain name.

(2) Access-control-allow-credentials

This field is optional. Its value is a Boolean value that indicates whether the cookie is allowed to be sent. By default, cookies are not included in Cors requests. Set to true , that is, the server is explicitly licensed, and the cookie can be included in the request and sent to the server. This value can only be set to true , if the server does not send a cookie browser, delete the field.

(3) Access-control-expose-headers

This field is optional. Cors request, XMLHttpRequest the object's getResponseHeader() method can only get 6 basic fields:,,,, Cache-Control Content-Language Content-Type Expires Last-Modified , Pragma . If you want to get the other fields, you must Access-Control-Expose-Headers specify them inside. The above example specifies that the getResponseHeader(‘FooBar‘) FooBar value of the field can be returned.

3.2 Withcredentials Properties

As mentioned above, cors requests do not send cookies and HTTP authentication information by default. If you want to send the cookie to the server, on the one hand, the server agrees, specify the Access-Control-Allow-Credentials field.

access-control-allow-credentials:True

On the other hand, developers must open properties in AJAX requests withCredentials .

var = New XMLHttpRequest (); XHR. = true ;

Otherwise, the browser is not sent even if the server agrees to send a cookie. Alternatively, the server requires a cookie to be set and the browser will not process it.

However, if the withCredentials setting is omitted, some browsers will still send cookies together. At this point, you can explicitly close withCredentials .

XHR. = false ;

It is important to note that if you want to send a cookie, you Access-Control-Allow-Origin cannot set it to an asterisk, and you must specify an explicit domain name that is consistent with the requested page. At the same time, the cookie still follows the same-origin policy, only the cookie that is set by the server domain name is uploaded, the cookie of the other domain name is not uploaded, and the document.cookie cookie under the server domain name cannot be read in the original page code (cross source).

Iv. non-Simple Request 4.1 Pre-inspection request

Non-trivial requests are requests that have special requirements for the server, such as the request method, PUT or the DELETE Content-Type type of the field application/json .

A cors request that is not a simple request, adds an HTTP query request, called a preflight request (preflight), before the formal communication.

The browser asks the server first, whether the domain name in which the current page resides is in the server's license list, and which HTTP verbs and header information fields can be used. The browser will make a formal request only if the answer is confirmed, otherwise it will be an XMLHttpRequest error.

The following is a JavaScript script for a browser.

varUrl= ' Http://api.alice.com/cors ';varXhr= New XMLHttpRequest();Xhr.Open( ' PUT ',Url, true);Xhr.setrequestheader( ' X-custom-header ', ' value ');Xhr.Send( );

In the above code, the HTTP request method is PUT , and sends a custom header message X-Custom-Header .

The browser discovers that this is a non-trivial request, and automatically issues a "preflight" request, requiring the server to confirm that it can request it. The following is the HTTP header information for this "preflight" request.

Options/cors http/1.1Origin:Http://api.bob.comAccess-control-request-method:PUTaccess-control-request-headers:X-custom-headerHost:Api.alice.comAccept-language:En-USConnection:Keep-aliveuser-agent:mozilla/5.0 ...

The request method for a preflight request is OPTIONS to indicate that the request is for questioning. In the header information, the key field is the Origin source from which the request came from.

In addition Origin to fields, the header information for a preflight request consists of two special fields.

(1) Access-control-request-method

This field is required to list which HTTP methods are used by the browser's cors request, as the example above PUT .

(2) Access-control-request-headers

The field is a comma-delimited string that specifies the header information field that the browser cors request will send extra, as the example above X-Custom-Header .

4.2 Responses to pre-test requests

After the server receives a "preflight" request, it checks Origin , Access-Control-Request-Method and after the Access-Control-Request-Headers fields, confirms that it allows cross-origin requests to respond.

http/1.1 OKDate:Mon, Dec 01:15:39 GMTServer:apache/2.0.61 (Unix)Access-control-allow-origin:Http://api.bob.comAccess-control-allow-methods:GET, POST, PUTaccess-control-allow-headers:X-custom-headerContent-type:text/html; Charset=utf-8content-encoding:Gzipcontent-length:0keep-alive:timeout=2, max=100Connection:Keep-aliveContent-type:Text/plain

In the above HTTP response, the key is the Access-Control-Allow-Origin field, which indicates that the http://api.bob.com data can be requested. The field can also be set to an asterisk, which means agreeing to any cross-origin request.

Access-control-allow-origin:*

If the browser negates the "preflight" request, a normal HTTP response is returned, but there is no cors-related header information field. At this point, the browser will assume that the server does not agree with the preflight request and therefore triggers an error that is XMLHttpRequest captured by the object's onerror callback function. The console will print out the following error message.

XMLHttpRequest Cannot load HTTP://Api.Alice.Com.Origin http://Api.Bob.COM is isn't allowed by Access-Control-Allow-Origin.

Other Cors-related fields for the server response are as follows.

Access-control-allow-methods:GET, POST, PUTaccess-control-allow-headers:X-custom-headeraccess-control-allow-credentials:TrueAccess-control-max-age:1728000

(1) Access-control-allow-methods

This field is required, and its value is a comma-delimited string that indicates the method that the server supports for all cross-domain requests. Note that all supported methods are returned, not just the one requested by the browser. This is to avoid multiple "preflight" requests.

(2) Access-control-allow-headers

If a browser request includes a Access-Control-Request-Headers field, the Access-Control-Allow-Headers field is required. It is also a comma-delimited string that indicates all header information fields supported by the server, not limited to the fields requested by the browser in preflight.

(3) Access-control-allow-credentials

This field has the same meaning as a simple request.

(4) Access-control-max-age

This field is optional to specify the validity period for this preflight request, in seconds. In the result, the validity period is 20 days (1.728 million seconds), which allows the cache to be cached for 1.728 million seconds (that is, 20 days), during which time there is no need to issue another preflight request.

4.3 Normal request and response of the browser

Once the server passes the "preflight" request, each subsequent browser's normal cors request, like a simple request, will have a Origin header information field. Server response, there will also be a Access-Control-Allow-Origin header information field.

The following is a normal cors request for the browser after the "preflight" request.

Put/cors http/1.1Origin:Http://api.bob.comHost:Api.alice.comX-custom-header:ValueAccept-language:En-USConnection:Keep-aliveuser-agent:mozilla/5.0 ...

The fields for the header information above Origin are automatically added by the browser.

The following is a normal response from the server.

Access-control-allow-origin:Http://api.bob.comContent-type:text/html; Charset=utf-8

In the header information above, the Access-Control-Allow-Origin fields are necessarily included in each response.

V. Comparison with the JSONP

Cors uses the same purpose as JSONP, but is more powerful than JSONP.

JSONP only supports GET requests, Cors supports all types of HTTP requests. The advantage of JSONP is that it supports older browsers and can request data from sites that do not support cors.

Cross-domain resource sharing CORS detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.