Cookies with CORS

Posted on by By Nikhilesh, in Javascript | 0

Cookies with CORS

CORS stands for Cross-Origin Resource Sharing and this is what wikipedia has to say about it.

Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated.

Once CORS is enabled, many resources can be shared easily apart from cookies. Sharing cookies is not straight forward. It might be particularly useful when you need to authenticate a user just using ajax and do not want to reload the page for some reason.

Sharing Cookies

For sharing cookies, we just need to set withCredentials on XHR object to true. Now auth info can be sent with request and the Set-Cookie response header will be respected by the browser.

Using jQuery

The following code shows how to do it in jQuery.

var post = $.ajax({
    type: 'POST',
    url: 'https://foobar.com',
    xhrFields: {
        withCredentials: true
    }
});

post.done(function (data) {
    console.log(data);
})

Or $.ajaxPrefilter can be used to set it globally

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

As stated on jQuery’s website, you will need jQuery 1.5.1+ for this to work.

ServerSide Changes

On server side, you just need to set correct Access-Control-* response headers:

Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, *
logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments