Cross-domain cors principle and invocation specific examples

Source: Internet
Author: User
Tags http authentication send cookies

Original: https://www.cnblogs.com/keyi/p/6726089.html

The previous blog introduced the JSONP principle, its insufficiency, is only to use get submit, if the amount of data transmitted, this JSONP way to break the dish. Then this blog will introduce another cross-domain introduction scenario-cors.

The relative jsonp,cors supports post submissions, and the implementation is often simple, and the cors principle only needs to inject Access-control-allow-origin into the header header of the response. This allows the browser to detect the Access-control-allow-origin in the header, so that it can operate across domains.

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.

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 xhr = new XMLHttpRequest();xhr.withCredentials = 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.withCredentials = 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.

var URL=' Http://api.alice.com/cors ';var xhr=NewXMLHttpRequest(;xhr.open ( ' PUT ' true ;xhr.setrequestheader ( ' 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 200 OKDate: Mon, 01 Dec 2008 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 not 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.

--------------------------------------------------------------------------------------------------------------- The------is implemented as follows: The front desk uses normal Ajax submissions, as with normal access, without changes.
$.ajax ({   URL:"http://localhost:8080/crcp/rcp/t99eidt/testcors.do",   async:false  ,   type:"POST",   success:function (data) {   var a=json.parse (data);   var html=json.stringify (a.resultset);   $ ("#testcors"). HTML (HTML);   },   error:function () {   alert ("error");   }   
The server action method is as follows:
 Public voidTestcors ()throwsexception{jsonobject Jsonobject=NewJsonobject (); List List=NewArrayList ();  for(inti=0;i<4;i++) {Map Parammap=NewHashMap (); Parammap.put ("Bank_no", 100+i); Parammap.put ("Money_type", i); Parammap.put ("Bank_name", "Test Code" +i); Parammap.put ("Bank_type", i); Parammap.put ("Bank_status", 0); Parammap.put ("En_sign_ways", 1);  List.add (PARAMMAP); } Jsonarray rows=jsonarray.fromobject (list); Jsonobject.put ("RESULTSET", rows); HttpServletRequest Request=servletactioncontext.getrequest (); HttpServletResponse Response=Servletactioncontext.getresponse (); Response.setheader ("Access-control-allow-origin", "*"); Response.setcharacterencoding ("UTF-8"); Writer out=Response.getwriter ();  System.out.println (Jsonobject.tostring ());  Out.write (Jsonobject.tostring ()); 
Response.setheader ("Access-control-allow-origin", "*"); In this code * code, the server allows anyone to access it. Of course, you can set the domain name of the specified access. For example, allow only HTTP://LOCALHOST:8080/CRCP access under this domain.    Then replace the * with the domain name. The response graph is as follows: Cors is relatively simple to implement, but the disadvantage is that it supports limited browsers. The currently supported browser versions are as follows

Cross-domain cors principle and invocation specific examples

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.