Detailed cross-domain CORS (rpm)

CORS is a W3C standard, stands for "Cross-Origin Resource Sharing" (Cross-origin resource sharing).

It allows the browser to cross the source server, issued a XMLHttpRequestrequest to overcome the AJAX only homologous restricted use.

This paper describes the internal mechanisms of CORS.

I. Introduction

CORS need to support both browser and server. Currently, all browsers support this feature, IE browser can not be less than IE10.

CORS entire communication process, the browser is done automatically, without user intervention. For developers, there is no difference AJAX communication CORS communicate with homologous, exactly as it was. Once AJAX browser cross-origin request, it will automatically add some additional header information, and sometimes more than a request for additional time, but users do not have feelings.

Therefore, communication is the key to achieving CORS server. CORS long as the server implements the interface, you can communicate across the source.

Second, two kinds of requests

CORS browser requests into two categories: a simple request (simple request) and requesting non-simple (not-so-simple request).

As long as both of the following two conditions belong to a simple request.

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

  • HEAD
  • GET
  • POST

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

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type: three limited value application/x-www-form-urlencoded, multipart/form-data,text/plain

Who do not meet the above two conditions, it is non-simple request.

Browsers handle both of these requests, it is not the same.

Third, a simple request

3.1 Basic Process

For a simple request, the browser sent directly CORS request. Specifically, it is the first information, the addition of a Originfield.

Here is an example of cross-source browser found this AJAX request is a simple request, automatically in the header information in to add a Originfield.


GET /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

The above header information, Origina field for describing, which source (port protocol name + +) from this request. Server based on this value, the decision whether to grant the request.

If the Originspecified source, not within the scope of the license, the server returns a normal HTTP response. Browser found this response header information does not contain Access-Control-Allow-Originfield (see below), you know wrong, so throw an error, is XMLHttpRequesta onerrorcallback function to capture. Note that this error code is not recognized by the state, because the HTTP response status code might be 200.

If the Originresponse to the domain name specified in the license, are returned by the server, a few extra header field.


Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8

The above header information, the three of CORS request related fields, are to Access-Control-begin with.

(1)Access-Control-Allow-Origin

This field is required. Its value is either request Originthe value of the field, either a *, acceptance request any domain.

(2)Access-Control-Allow-Credentials

This field is optional. Its value is a Boolean value that indicates whether to allow sending Cookie. By default, Cookie CORS not included in the request. Is set true, it means that the server explicit permission, Cookie can be included in the request sent to the server. This value can only be set trueif the server is not sent by the browser Cookie, you can delete the field.

(3)Access-Control-Expose-Headers

This field is optional. When the request CORS, XMLHttpRequestan object getResponseHeader()method can only get six basic Cache-Controlfields: Content-Language, Content-Type, Expires, Last-Modified, Pragma, . If you want to get the other fields, you must Access-Control-Expose-Headersspecify the inside. Examples of the above specified, getResponseHeader('FooBar')can be returned FooBarvalue of the field.

3.2 withCredentials property

Speaking of the above, CORS request not to send default HTTP Cookie and authentication information. If you want Cookie to the server, the server agree on the one hand, the specified Access-Control-Allow-Credentialsfield.


Access-Control-Allow-Credentials: true

On the other hand, the developer must open the AJAX request withCredentialsattribute.


var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

Otherwise, even if the server agree to send Cookie, the browser will not be sent. Alternatively, the server requirements set Cookie, the browser will not be processed.

However, if you omit withCredentialssettings, some browsers will send Cookie together. In this case, it is explicitly closed withCredentials.


xhr.withCredentials = false;

Note that, if you want to send Cookie, Access-Control-Allow-Originyou can not set an asterisk, you must specify clear, consistent and domain name requests a web page. Meanwhile, Cookie still follow the same-origin policy, only with Cookie domain name server settings will be uploaded, Cookie and other domain names will not upload, and (cross-source) the original page code document.cookiecan not be read in the Cookie domain name server.

Fourth, non-simple request

4.1 preflight request

Non-simple request that there are special requirements for the server request, such as is PUTor DELETE, or Content-Typetype field is application/json.

Non-simple request CORS request, before the official communication, increase an HTTP query request, called "preflight" request (preflight).

The browser first asks the server, where the domain of the current web page whether in the license server list, and which HTTP verbs can and header field use. Only positive response, the browser will issue a formal XMLHttpRequestrequest, otherwise an error.

The following is a JavaScript script for a browser.


var url = 'http://api.alice.com/cors';
var xhr = 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 information X-Custom-Header.

The browser sees that this is a non-simple request, it automatically sends a "preflight" request to the server can confirm this request. The following is the HTTP header "preflight" request.


OPTIONS /cors HTTP/1.1
Origin: http://api.bob.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

Request method "preflight" request is used OPTIONSto indicate that the request is used to query. Head inside information, key segments are Origin, which represents a request from the source.

In addition to Originthe fields, the header information "preflight" requests comprises two special fields.

(1)Access-Control-Request-Method

This field is required for lists of CORS browser HTTP request method which will be used, the examples are PUT.

(2)Access-Control-Request-Headers

This field is a comma-separated string that specifies the browser request CORS extra header field transmitted, the case is X-Custom-Header.

4.2 respond to preflight requests

Server receives a "pre-screening" after the request, examined Origin, Access-Control-Request-Methodand Access-Control-Request-Headersafter field, acknowledge allow cross-origin requests, we can respond.


HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://api.bob.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

The above HTTP response, the key is a Access-Control-Allow-Originfield indicating http://api.bob.comcan request data. This field can be set to an asterisk, it agreed any cross-origin requests.


Access-Control-Allow-Origin: *

If the browser denied "preflight" request, it returns a normal HTTP response, but no related CORS header field. In this case, the browser will identify the server does not agree preflight request, thus triggering an error, the XMLHttpRequestobject onerrorcaptured callback function. The console will print out the following error message.


XMLHttpRequest cannot load http://api.alice.com.
Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin.

Server response CORS other relevant fields below.


Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1728000

(1)Access-Control-Allow-Methods

This field is required, its value string is a comma-separated cross-domain requests indicating that all methods that the server supports. Note that the return of all supported methods, rather than simply the method that the browser requests. This is to avoid multiple "preflight" request.

(2)Access-Control-Allow-Headers

If the browser request includes Access-Control-Request-Headersa field, the Access-Control-Allow-Headersfield is required. It is also a comma delimited string indicating the server supports all the header field is not limited to a browser request field in the "pre-screening" in.

(3)Access-Control-Allow-Credentials

The same meaning in the field with a simple request.

(4)Access-Control-Max-Age

This field is optional pre-screening is used to specify the current valid request, in seconds. Above results, the period is 20 days (1,728,000 seconds), allowing the cache to respond to the article 1728000 seconds (i.e., 20 days), during which the preflight not issue another request.

Normal requests and responses 4.3 browser

Once the server through a "preflight" request, after each time the browser requests a normal CORS, as it related to a simple request, there will be a Originheader field. Server response, but also will have a Access-Control-Allow-Originheader field.

Here it is after "preflight" request, normal CORS browser requests.


PUT /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
X-Custom-Header: value
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

The above header information Originfield is automatically added to the browser.

The following is a normal server response.


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

Head above information, the Access-Control-Allow-Originfield is contained in each response are bound.

Fifth, compared with the JSONP

CORS JSONP with the same purpose, but more powerful than JSONP.

Only supports JSONP GETrequest, CORS support all types of HTTP requests. JSONP advantage is to support older browsers, and can request data from the CORS site does not support.

 

 

Transfer: https://www.ruanyifeng.com/blog/2016/04/cors.html

Guess you like

Origin www.cnblogs.com/guanbin-529/p/12616605.html