Blog

Cookies With My CORS

Since early implementations of the CORS (Cross-Origin Resource Sharing) specification, developers have been eager to drop the JSONP hack in favor of a proper cross-domain request.

CORS means that XHRs are sent with the ORIGIN header, and expect the server to include that ORIGIN (or *) in the Access-Control-Allow-Origin response header. For requests other than GET and some POST, this is done as a "preflight". The browser/server allow matched requests and the server responds with the cross-domain goodness.

Omnom Cookies

But what about HTTP Auth and Cookies? No problem. Just set withCredentials on the XHR object to true. Cookies and auth can be sent along with the request, and the Set-Cookie response header is respected by the browser.

jQuery

Here's a quick example (in CoffeeScript for terseness and radness) that enables CORS support in jQuery, sets withCredentials to true, and fires off a request. (Note: this is not supported by IE, you'll need the redundant XDomainRequest object for that.)

$.support.cors = true

post =
  type: 'POST'
  url: 'https://remote.bar'
  data: myData
  xhrFields:
    withCredentials: true
  success: (data) ->
    console.log 'tada', data
  error: (e) ->
    throw 'error'

$.ajax post

Fun Tip: You can also add an $.ajaxPrefilter to essentially add CORS support to all of your jQuery AJAX requests:

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
  options.crossDomain ={
    crossDomain: true
  };
  options.xhrFields = {
    withCredentials: true
  };
});

Considerations for The Server

Just set the correct Access-Control response headers:

Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://origin.foo
Access-Control-Allow-Headers: Content-Type, *

For more reading check out Mozilla's 2009 article from when CORS support showed up in Firefox.