Another solution for cross-domain--cors (cross-origin Resource sharing) cross-domain resource sharing

Source: Internet
Author: User
Tags http authentication in domain

Using Ajax in our daily project development, traditional AJAX requests can only get resources under the same domain name, but HTML5 breaks this limit and allows Ajax to initiate cross-domain requests. A browser can initiate cross-domain requests, such as an external image or script that you can chain outside. But JavaScript scripts cannot get the content of these resources, it can only be executed or rendered by the browser. The main reason is that the browser restricts the cross-site requests originating in the script for security reasons. (same-Origin policy, that is, JavaScript or cookie can only access content under the same domain). Cross-domain solutions have multiple jsonp, Flash, IFrame, and, of course, cors (cross-domain resource sharing, cross-origin Resource sharing) today to learn about the principles of cors and how to use them.

I. Overview of Cors

Cross-origin resource sharing standard by adding a series of HTTP headers, the server can declare that the source can access various resources (including CSS, pictures, JavaScript scripts, and other classes of resources) on the server through a browser. In addition, for HTTP request methods that can have a devastating effect on server data (especially HTTP methods other than GET, or with some MIME-type post requests), the standard strongly requires that the browser must first send a pre-request in the options request (preflight Request) To learn about the HTTP methods supported by the server side for cross-origin requests. The actual HTTP request method is used to send that real request in the case of a confirmation that the server allows the cross-origin request. The server side can also notify the client whether it is necessary to send credit information (including Cookies and HTTP authentication related data) along with the request.

Ii. the principle of cors

For example: a WEB application in Domain A (http://a.example) has introduced a picture resource (http://b.foo/image.jpg) from the domain name B (http://b.foo) site through the tag. This is a cross-domain request that requests an HTTP header that contains origin:http://a.example if the returned HTTP header contains a response header Access-control-allow-origin:http://a.example (or Access-control-allow-origin:http://a.example), which indicates that Domain B accepts a request under domain B, then the picture is loaded. Otherwise, the request is rejected.

Three, Cors cross-domain Request control method

1.http Request Header

Origin: A normal HTTP request will also be provided, which is used specifically as Origin information for the back-end alignment in Cors, indicating the source domain.

Access-control-request-method: The next method of request, such as put, delete, etc.

Access-control-request-headers: Custom headers, all headers set with the setRequestHeader method will be included in this header in a comma-separated form

2.http Response Head

The browser then determines whether to send a non-simple request based on the return value of the server. The simple request was preceded by a direct send, but adding an Origin field indicates the origin of the cross-domain request. After the server finishes processing the request, it returns the result with the following control field

Access-control-allow-origin: A domain that allows cross-domain access, either as a list of domains or as a wildcard "*". Note here that the origin rule is only valid for the domain name and is not valid for the subdirectory. That is, http://foo.example/subdir/is invalid. But different subdomains need to be set separately, here the rules can refer to the same-origin policy

Access-control-allow-credentials: If the request is allowed with authentication information and the XMLHttpRequest request's Withcredentials flag is set to True, the browser passes the data to the script program.

Access-control-expose-headers: Allow script access to the return header, after the request succeeds, the script can access the information of these headers in XMLHttpRequest

Access-control-max-age: The number of seconds to cache this request. In this timeframe, all requests of the same type will no longer send a preflight request, but use the returned header directly as a basis for judging, which is very useful to greatly optimize the number of requests

Access-control-allow-methods: Allowed request methods, separated by commas

Access-control-allow-headers: Allow custom headers, separated by commas, case insensitive

Four, browser support situation

Supported in most modern browsers, browsers that support (partially support) cors protocols have ie8+, firefox5+, chrome12+, safari4+, and almost full support for mobile.

Note: Internet Explorer 8, 9 uses the Xdomainrequest object to implement Cors.

V. Cors Use Cases

Case environment: Client uses jquery, Server WEBAPI (2.2). Because I use the. NET language, the server uses WEBAPI to demonstrate.

Start by creating a new Webapi project, which is not a step at the beginning, and then use NuGet to install the cors-enabled extension components.

Install-package Microsoft.AspNet.WebApi.Cors

Then open the WebConfig.cs profile class under the App_start ask price clip, configure a global cors in the Register method, for convenience I configure some parameters in the Web. config configuration file

If you do not want to use global cors, you can configure it on a method or Apicontroller: [Enablecors (Origins: "*", Headers: "*", Methods: "*")], you can use specific parameters, Multiple parameters are separated by commas, needless to say, a comma is definitely. Origins domain name to bring HTTP top-level domain name. You need to add a using System.Web.Http.Cors;

As a general request, the client's AJAX requests do not need to be changed, only a slight change in the service side is required.

Client JS code: Apirootpath is the top-level domain name of my pre-set API.

$.ajax ({url:apirootpath+ "Api/account/register", type:"POST", data: {"UserName": Mobile,"Password": pwd}, DataType:"JSON", Success:function(data) {if(Data. state = =true) {regsuccess (mobile, PWD); } Else {                            $("#errorText"). HTML (data.                            Message); $("#registerBtn"). Text ("register")); }                    }                });

Because I configured the global Cors method, and the service side is not special, and ordinary Web site (not across) the wording of the same, this is not posted here.

What if you need to authenticate the request? We implement this verification by a cookie.

$.ajax ({url:apirootpath+ "Api/account/login", type:"POST", data: {"UserName": UserName,"Password": Password}, Crossdomain:true, Xhrfields: {withcredentials:true}, DataType:"JSON", Success:function(data) {if(Data. state = =true) {mlogin (userName, password); } Else {                            $("#loginBtn"). Text ("Login"); $("#errorText"). HTML (data.                        Message); }                    }                });

Note This two words: Crossdomain:true,xhrfields: {withcredentials:true}

VI: Security Risks

If the program ape lazy set Access-control-allow-origin to: access-control-allow-origin: * Allow any cross-domain requests from any domain, so long there is the possibility of DDoS attacks.

I want to add ...

Vii. If there are deficiencies, please note and Add.

Reprint please indicate the source, thank you.

Another solution for cross-domain--cors (cross-origin Resource sharing) cross-domain resource sharing

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.