HTML5 Security: CORS (cross-domain resource sharing) Introduction

Source: Internet
Author: User

Preface: Like Cors for the modern front-end so important technology in the domestic basically incredibly few people use and mention, in Baidu or Google search cors, found in the Chinese article is another kind of satellite positioning technology Cors Introduction, let me wait for the front-end classmate sentiment why (contrast up, Using Google to search foreign articles, is basically a cross-domain resource sharing introduction, illustrates the front-end technology in the domestic and foreign environment and development of the huge gap.

My previous article, "Using HTML5 for Face recognition", mentions that "face.com implements CORS(cross-domain resource sharing). CORS Systems can basically expose the server to Ajax calls to files on other domains . This is a great feature and I want more services to be able to use it. "In the implementation of this article, we are free to use the JS code of our own domain to invoke face.com via Ajax . API, which is a wonderful way, and it's hard for us to do that before.

I will introduce and introduce cors, and I hope to help you.

definition

CORS is actually a short time, it is defined on Wikipedia: cross-domain resource sharing (CORS ) is a technical specification of a Web browser that defines a way for a website to access its resources from different domains. This access is prohibited by the same-origin policy. The cors system defines a way for browser and server interaction to determine whether cross-domain requests are allowed. It is a compromise, with greater flexibility, but more secure than simply allowing all these requirements to be made.

The official document is still a working draft, but is moving in the direction of the recommendation.

In short, cors is meant to enable Ajax to achieve controllable cross-domain access.

Solutions for the past

Previously, cross-domain access could be achieved through JSONP, Flash, or server relay, but now we have cors.

Compared with JSONP, Cors is undoubtedly more advanced, convenient and reliable.

1. JSONP can only implement get requests, and Cors supports all types of HTTP requests.

2, using cors, developers can use ordinary XMLHttpRequest to initiate requests and obtain data, than JSONP have better error handling.

3, JSONP is mainly supported by the old browser, they often do not support cors, and most modern browsers have already supported Cors (this section will be described in the Post-browser support Section).

Detailed content

To use cors, we need to know how to use the front-end and server-side methods.

1. Front-end

Before we used Ajax, the code was similar to the following:

[HTML]View Plain Copy
    1. var xhr = new XMLHttpRequest ();
    2. Xhr.open ("GET", "/hfahe", true);
    3. Xhr.send ();

The "/hfahe" here is the relative path to this domain.

If we were to use Cors, the relevant AJAX code might look like this:

[HTML]View Plain Copy
    1. var xhr = new XMLHttpRequest ();
    2. Xhr.open ("GET", "Http://blog.csdn.net/hfahe", true);
    3. Xhr.send ();

Note that the difference between the code and the previous one is that the relative path is replaced by the absolute path of the other domain, which is the interface address you want to access across domains.

We must also provide browser fallback feature detection and support to avoid situations where browsers are not supported.

                                                [HTML]View Plain Copy
  
 
  1. function Createcorsrequest (method, url) {
  2. var xhr = new XMLHttpRequest ();
  3. if ("Withcredentials" in xhr) {
  4. //This is the case for cors support
  5. //Check if the XMLHttpRequest object has a "withcredentials" property
  6. //"withcredentials" exists only in XMLHTTPRequest2 object
  7. Xhr.open (method, URL, true);
  8.    
  9. } else if (typeof!= "undefined") {
  10.    
  11. //Check if support for XDOMAINREQUEST,IE8 and IE9 is supported
  12. //Xdomainrequest only in IE, is the way IE is used to support Cors requests
  13. xhr = new xdomainrequest ();
  14. Xhr.open (method, URL);
  15.    
  16. } else {
  17.    
  18. //Otherwise, the browser does not support Cors
  19. xhr = null;
  20.    
  21.   }  
  22. return XHR;
  23. }  
  24.    
  25. var xhr = createcorsrequest(' GET ', url);
  26. if (!xhr) {
  27. throw new Error (' CORS not supported ');
  28. }  

Now if you use the above script directly to request, you will see the browser console error as follows:

The error is clearly shown because we have not set the Access-control-allow-origin header yet.

2. Server

The server-side support for cors is mainly done by setting up Access-control-allow-origin. If the browser detects the appropriate settings, it can allow Ajax for cross-domain access.

There are many ways to set up HTTP headers, http://enable-cors.org/This article on the various server and language settings are described in detail, below we mainly introduce the Apache and PHP setup methods.

Apache:apache needs to use the Mod_headers module to activate the HTTP header settings, which are activated by default. You only need to add the following to the <directory> of the Apache configuration file, <location>, <Files> or <VirtualHost> configuration:

[HTML]View Plain Copy
    1. Header Set Access-control-allow-origin *

PHP: Just use the following code settings.

[HTML]View Plain Copy
    1. <? PHP   
    2. header ("access-control-allow-origin:*");

The meaning of the above configuration is to allow any domain-initiated requests to obtain data from the current server. Of course, there is a great danger that malicious sites may attack our servers through XSS. So we should try to be targeted to restrict the source of security, for example, the following setting makes only http://blog.csdn.net this domain to access the server's API across domains.

[HTML]View Plain Copy
    1. access-control-allow-origin:http://blog.csdn.net

Browser Support Scenarios


For each browser's support for cors (green support, data Source: http://caniuse.com/cors), it looks pretty optimistic. Mainstream browsers have basically provided support for cross-domain resource sharing, so it is common for cors to be used abroad.

As mentioned earlier, IE8 and IE9 can, to some extent, provide support for the same functionality through Xdomainrequest.

use case

There are many platforms that support cors abroad, such as:

Google apiclient Library for JS

Google Cloudstorage

Face.com API

Future

From the support of all browsers, Cors will be the standard solution for future cross-domain access. Whether it is cross-domain access between your own servers or an open platform that provides APIs to third parties, this unified solution will be used because it is simple and efficient and is supported by all major browsers. It's very important and will make our network more open.

Reference Articles

Cors FORXHR in IE10

USING CORS

Original articles, reproduced please specify: from Shiyute's blog (http://blog.csdn.net/hfahe)

HTML5 Security: CORS (cross-domain resource sharing) Introduction

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.