Thursday, June 20, 2013

AJAX calls to different servers (CORS)

Developing modern HTML applications, sometimes you have the need to send an AJAX request data to another server. Unfortunately, this could be a security issue. Therefore all browsers implement the Same origin policy, which prevents such calls.
But what, if you really need it? The rescue is Cross-origin resource sharing (CORS). The principle is quite easy: the browser sends with the AJAX request an additional HTTP header:
Origin: http://www.foo.com
The server can analyze the header. If it decides to fulfill the request, it adds another header:
Access-Control-Allow-Origin: http://www.foo.com
If the server decides to trust all clients, it can also return
Access-Control-Allow-Origin: *
But if you send the AJAX request from a page with origin http://www.foo.com, while the server replies with http://www.bar.com, you cannot read the response.

Browser support

All major browsers support CORS with XMLHttpRequest. All but IE8 or IE9. These IE versions use a slightly different approach. When you want CORS, you have to use another object instead: XDomainRequest. Fortunately at least its interface is similar to XMLHttpRequest.

JQuery

JQuery uses for AJAX calls always XMLHttpRequest. The request to use XDomainRequest when needed was rejected. Instead it is recommended to use a JQuery plugin. For this purpose I found 2 implementations:
Both worked for me, but with jQuery.iecors I had problems receiving errors. At least in my tests the error function was not called. Therefore I finally decided to use jQuery.XDomainRequest.

CORS and ASP.NET Web Api

For supporting CORS with ASP.NET Web Api, you need to add the Access-Control-Allow-Origin header to the response. One way is to implement a custom message handler for this purpose. Carlos Figueira blogged a good description, how to do this.

2 comments:

  1. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    ReplyDelete
  2. I read this article. I think You put a lot of effort to create this article. I appreciate your work.
    thesis Writing Service

    ReplyDelete