Cross-Origin Resource Sharing

July 17, 2011, 8:03 p.m.

If you ever tried to make a request to a different domain using Javascript inside a web browser, you've probably encountered what's known as the same origin policy. This security feature basically blocks all calls that a script tries to make to an origin (protocol + host + port) that is different from its own.

For communication across sub-domains, the document.domain feature can be used. Over time, a number of ways to achieve cross-domain communication have popped up but most of them are hacks (fragments, window.name, JSONP, etc.). While there are some libraries that abstract these hacks and choose the most appropriate method for the given browser (e.g. easyXDM), it's time to start using newer technologies that provide explicit support for cross domain calls.

HTML5 comes with a more generic cross-document-messaging mechanism via postMessage that allows scripts to send messages to other windows and documents. But there is another exciting way to explicitly allow cross-domain HTTP requests on the server side: a W3C Working Draft called Cross-Origin Resource Sharing. The idea is extremely simple. A domain can choose to allow calls from different domains by adding Access-Control- HTTP headers to its response. Example response:

HTTP/1.1 200 OK
Date: Sun, 17 Jul 2011 17:37:32 GMT
Server: Apache/2.2.16 (Debian)
Content-Type: application/json; charset=utf-8
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Headers: Content-Type,Accept

This allows any script on any domain (-Allow-Origin: *) to make requests to this server using GETs and POSTs and some headers to specify content types (xml, json, javascript, etc.). Cool, eh?

Cross-Origin Resource Sharing (CORS) allows for very fine-grained access control and is supported by a lot of popular browsers (basically everyone but Opera). Here's how you implement CORS in IIS and ASP.Net.

about