Cross-origin request details

Source: Internet
Author: User
Tags subdomain name
Same-origin policy

One restriction of AJAX is the same origin policy. It requires that all requests come from the same domain name and subdomain name, and the ports of the addresses must be consistent. The main reason is security considerations: When an Ajax request is sent, all requests are sent together with the cookie information of the primary domain. That is to say, for remote services, if a request comes from a user after login, if there is no same-origin policy restriction, attackers may obtain emails in your Gmail, your fackbook status, or your Twitter friends. This is a very serious security issue.

However, although the same-origin policy is proposed for security reasons, it also makes some inconvenience for developers who really need to obtain legal data across domains. Technologies such as Adobe Flash and Java have already begun to solve this problem, usually cross-domain policy files. Currently, the CORS (cross-origin Resource Sharing) standard is also proposed for Ajax.

CORS

CORS breaks the same-source policy restrictions and grants the front-end code the permission to access trusted remote services. Mainstream browsers support this specification, unless IE6 is used, it can be used very well.

Browsers that support CORS:

  • IE> = 8 (security required)
  • Firefox> = 3
  • Safari: fully supported
  • Chrome: fully supported
  • Opera: not supported

CORS is easy to use. To add your server as a trusted data source, add a few lines in the HTTP Response Header:

Access-control-allow-origin: example.com

Access-control-request-method: Get, post

The two header fields will verify the cross-origin get and post requests from example.com. Multiple values are separated by commas, just like the get and post values mentioned above. If you want to add multiple domain names, the domain names are listed in the access-control-allow-origin header, and each two domain names are separated by commas. If access requests from any domain are allowed, you must add wildcard characters (*) to the source (*).

For Some browsers, such as safari, it first initiates an options request to check whether the server allows cross-origin requests.

On the other hand, Firefox directly initiates a cross-origin request, but when the server does not configure the CORS header field, a security exception is thrown. Note the differences in browser behavior.

You can even use the access-control-allow-headers header field to authenticate custom request headers:

Access-control-request-headers: Authorization

This also means that the client can add a custom header to the Ajax request, for example, using oauth to sign the request:

VaR Req = new XMLHttpRequest ();

Req. Open ("Post", "/Endpoint", true );

Req. setRequestHeader ("Authorization", oauth_signature );

Xdomainrequest

Unfortunately, although CORS can work normally in IE 8 and later versions, Microsoft still chooses a different path, which is incompatible with specifications and ignores the standards set by the W3C Working Group. Microsoft uses its own object xdomainrequest to replace XMLHttpRequest for cross-origin communication. Its interface is very similar to XMLHttpRequest. It contains a series of constraints and restrictions, such as only the get and post methods, validation and custom fields, and support for "Content-Type: text/plain requests.

If you meet these restrictions, you can use the correct access-control header field and xdomainrequest in IE8 to implement CORS. The webpage can directly generate cross-Origin data requests in the browser, instead of using requests from the server to the server. Cross-origin requests must be approved by the webpage and server. By using the window object to create an xdomainrequest object and open the connection to a specific domain, you can enable a cross-origin request on the webpage. The browser sends an origin request header with the source value to request data from a server in a specific domain. If the access-control-allow-origin response header of the server response is * or the exact URL of the Request page, the browser completes the connection and can then use xdomainrequest to request data on the target server. Xdomainrequest is used as follows:

// 1. Create XDR object: var xdr = new XDomainRequest(); // 2. Open connection with server using GET method:xdr.open("get", "http://www.contoso.com/xdr.aspx");// 3. Send string data to server:xdr.send();

xdr.onload=function(){
var data=JSON.parse(xdr.responseText);
};

Xdomain supports onload, onerror, ontimeout, onprogress, and timeout methods.

Jsonp

Jsonp (JSON with padding) was standardized A long time ago, even before CORS. This is another way to capture data from a remote server. The principle is to create a script tag. The requested external file contains a piece of JSON data. The data is returned by the server and packaged as parameters in a function call. Script tag acquisition of script files is not subject to cross-origin restrictions. all browsers support this technology.

The following example shows a script tag pointing to a remote service:

<SCRIPT src = "http://example.com/data.json"> </SCRIPT>

The requested file data. JSON contains a JSON object packaged in a function call:

Jsoncallback ({"data": "foo "})

In this case, we define a global function. After the script is loaded, this function will be called:

Window. jsoncallback = function (result ){

// Process the related logic of the returned result

}

Jquery wraps this process into a concise API:

jQuery.getJSON("http://example.com/data.json?callback=jsonCallback",function(result){console.log(result);});

Or

  $.ajax({          url:"http://crossdomain.com/services.php",          dataType:‘jsonp‘,          data:‘‘,          jsonp:‘callback‘,          success:function(result) {          },          timeout:3000      }); 

 

Jquery replaces the last question mark in the above URL with a temporary function with a random name created by it. The server will obtain this callback parameter and use this name as the callback function name to return it to the client.

References:

Javascript web rich application development based on MVC

Http://msdn.microsoft.com/zh-cn/library/dd573303%28v=vs.85%29.aspx

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.