HTML5 security: CORS Introduction

Source: Internet
Author: User
Tags net domain

Some important technologies such as CORS for the modern front-end are rarely used and mentioned in China. They search for CORS on Baidu or Google to find Chinese characters.ArticleThe introduction of CORS is basically another satellite positioning technology. In comparison, the foreign articles searched by Google are mostly about cross-origin resource sharing, shows the huge gap between front-end technology and development in domestic and foreign environments ).

As mentioned in my article "Implementing face recognition with HTML5", "face.com implementsCORS(Cross-origin resource sharing ). The CORS system allows the server to expose Ajax calls to files in other domains. This is a great feature and I hope more services can use it ." In the implementation method introduced in this article, we can freely use the Js of our own domain.CodeCalling face.com APIs through Ajax is a wonderful way, and it was hard to do so before.

So I will introduce and introduce CORS and hope to help you.

Definition

In fact, the emergence of CORS is not short. Its definition on Wikipedia is:CORSIs a technical specification for Web browsers. It defines a way for Web servers to allow web pages to access their resources from different domains. Such access is forbidden by the same-origin policy. The CORS system defines a way for the browser to interact with the server to determine whether cross-origin requests are allowed. It is a compromise with greater flexibility, but it is safer than simply allowing all of these requirements.

W3C official documentation is still working draft, but is moving towards W3C recommendation.

In short, CORS is generated to allow ajax to implement controllable cross-origin access.

Previous solutions

In the past, cross-origin access was implemented through jsonp, Flash, or server transit, but now we have CORS.

CORS is more advanced, convenient, and reliable than jsonp.

1. jsonp can only implement GET requests, while CORS supports all types of HTTP requests.

2. With CORS, developers can use common XMLHttpRequest to initiate requests and obtain data, which provides better error handling than jsonp.

3. jsonp is mainly supported by old browsers, which often do not support CORS, and most modern browsers have already supported CORS (This section introduces browser support in the following article ).

Details

To use CORS, we need to know how to use the front-end and server.

1. Front-end

In the past, we used Ajax. The code is similar to the following method:

[HTML]View plaincopyprint?

    1. VaR xhr = new XMLHttpRequest ();
    2. Xhr. Open ("get", "/hfahe", true );
    3. Xhr. Send ();
 
VaR xhr = new XMLHttpRequest (); xhr. Open ("get", "/hfahe", true); xhr. Send ();

"/Hfahe" is the relative path of the local domain.

If CORS is to be used, the relevant Ajax code may be as follows:

[HTML]View plaincopyprint?

    1. VaR xhr = new XMLHttpRequest ();
    2. Xhr. Open ("get", "http://blog.csdn.net/hfahe", true );
    3. Xhr. Send ();
 
VaR xhr = new XMLHttpRequest (); xhr. Open ("get", "http://blog.csdn.net/hfahe", true); xhr. Send ();

Note that the difference between the Code and the previous Code is that the relative path is replaced with the absolute path of other domains, that is, the interface address for cross-origin access.

We must also provide browser rollback detection and support to avoid browser unavailability.

[HTML]View plaincopyprint?

    1. function createcorsrequest (method, URL) {
    2. var xhr = new XMLHttpRequest ();
    3. If ("withcredentials" in xhr) {
    4. // in this case, CORS is supported
    5. // check whether the XMLHTTPRequest object has the "withcredentials" attribute.
    6. // "withcredentials" only exists in the xmlhttprequest2 object
    7. xhr. Open (method, URL, true);
    8. } else if (typeof! = "Undefined") {
    9. // otherwise, check whether xdomainrequest, IE8, and ie9 are supported.
    10. // xdomainrequest only exists in IE and is used by IE to support CORS requests.
    11. xhr = new xdomainrequest ();
    12. xhr. Open (method, URL);
    13. }else {
    14. // otherwise, the browser does not support CORS
    15. xhr = NULL;
    16. }
    17. return xhr;
    18. }
    19. var xhr = createcorsrequest ('get', URL);
    20. If (! Xhr) {
    21. throw new error ('cors not supported orted');
    22. }
Function createcorsrequest (method, URL) {var xhr = new XMLHttpRequest (); If ("withcredentials" in xhr) {// CORS is supported at this time. // check whether the XMLHTTPRequest object has the "withcredentials" attribute. // "withcredentials" only exists in the xmlhttprequest2 object xhr. open (method, URL, true);} else if (typeof! = "Undefined") {// otherwise, check whether xdomainrequest is supported. IE8 and ie9 support it. // xdomainrequest is only available in IE, is the method in which IE is used to support CORS requests xhr = new xdomainrequest (); xhr. open (method, URL);} else {// otherwise, the browser does not support CORS xhr = NULL;} return xhr;} var xhr = createcorsrequest ('get', URL ); if (! Xhr) {Throw new error ('cors not ororted ');}

If you directly use the above script for the request, you will see the console error in the browser as follows:

The error is obviously displayed because the access-control-allow-origin header is not set yet.

2. Servers

The server supports CORS mainly by setting access-control-allow-origin. If the browser detects the corresponding settings, AJAX can be allowed for cross-origin access.

There are many methods to set HTTP headers.

Apache: Apache requires the mod_headers module to activate HTTP header settings. It is activated by default. You only need to add the following content to the configuration of the Apache configuration file <directory>, <location>, <files> or <virtualhost>:

[HTML]View plaincopyprint?

    1. Header set access-control-allow-origin *
 
Header set access-control-allow-origin *

PHP: you only need to use the following code settings.

[HTML]View plaincopyprint?

    1. <? PHP
    2. Header ("access-control-allow-origin :*");
 
<? PHP header ("access-control-allow-origin :*");

The preceding configuration means that any request initiated by any domain can obtain the data of the current server. Of course, this is very dangerous. Malicious websites may attack our servers through XSS. So we should try to restrict the sources of security as far as possible, such as the settings below so that only the http://blog.csdn.net domain can access the server's API across domains.

[HTML]View plaincopyprint?

    1. Access-control-allow-origin: http://blog.csdn.net
 
Access-control-allow-origin: http://blog.csdn.net

Browser support


For various browsers for CORS support (green for support, data source: http://caniuse.com/cors), looks quite optimistic. Mainstream browsers have basically provided support for cross-origin resource sharing, so CORS is so common in foreign countries.

As mentioned above, IE8 and ie9 can provide support for the same function to some extent through xdomainrequest.

Use Cases

At present, there are many platforms that support CORS in foreign countries, such:

Google apiclient library for JS

Google cloudstorage

Face.com API

Future

From the support of all browsers, CORS will become a standard solution for cross-origin access in the future. Whether cross-origin access between servers or open platforms provide APIs for third parties, this unified solution is adopted because it is simple and efficient and is supported by all mainstream browsers. It is very important and will make our network more open.

References

CORS forxhr in ie10

Using CORS

Original article, reproduced Please note: from Jiang Yujie blog (http://blog.csdn.net/hfahe)

 

    • Logistics Distribution Network http://wlphw.com/QQ online: 471226865

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.