Tuesday, August 19, 2014

Cross domain jQuery ajax call with cookies



CORS ( Cross Origin Resource Sharing ) is a W3C spec which defines the way to communicate over cross domains from the browser.


Cross domain communication occurs when a service from domain A tries to connect with a service from domain B to retrieve some data. But traditionally browsers don't allow this sort of communication due to Same Origin Policy

By using the CORS, the Cross domain communication can be enabled from domain B's side by adding some more additional header values which will enable the browser to let domain A to access the services of domain B.

Following browser's support CORS
  • Internet Explorer 8+
  • Firefox 3.5+
  • Safari 4+
  • Chrome

By default standard CORS requests don't have cookies embedded with it. Therefore by setting the XMLHttpRequest’s <.withCredentials> attribute to true we can enable cookie transport with the request. This is the only thing that have to be done from the client side.

On the other hand we have to set some of the header values from the server side too. Those are

  1. Access-Control-Allow-Origin field indicates the origin of the request header. Wild card operator value doesn't work on all browsers.
  2. Access-Control-Allow-Headers param indicates the headers supported by autothe server. If any of the request which is not expecting any one of the listed values as headers, browser won't be displaying the content.  
  3. Access-Control-Allow-Methods param defines the comma delimited supported HTTP methods by server.
  4. Set the Access-Control-Allow-Credentials parameter value to true. This header field indicates that cookie should be included in request.


JQuery client code.

Server code.








1 comment:

  1. This link contains more info. http://www.html5rocks.com/en/tutorials/cors/

    ReplyDelete