Monday, October 14, 2013

Web API, JSON, AJAX, CORS, Chrome 500 error and Authentication–Oh My!

I have been working on a project that is using .Net 4.0 and MVC 4 with Web API. Web API is great and provides a lot of great functionality easily. We have needed to call our Web API from another domain though which introduces Cross Origin Resource Sharing (CORS) issues. Web API in 4.0 does not really support this so it has been causes us issues, you can configure IIS to work with it pretty easily.. In later version it will support it better. See the following links:

Web API VS 2013 (.Net 4.5 and later)

http://aspnetwebstack.codeplex.com/

Enabling Cross-Origin Requests in ASP.NET Web API

ASP.NET Web API: CORS support and Attribute Based Routing Improvements

However, if you are using 4.0 that is not much help to you. We have had to push through a few issues on this front. If you are testing with IE8 you will not see them as it does not care about CORS issues. If it is working in IE but not working in Chrome or FireFox here are some issues we have been working through:

 

Some calls return data others do not

Be default Web returns both XML and JSON formatted objects. If you are doing a browser based request (especially in Chrome) the default request asks for XML back. Look at what type of objects you are returning. If you are returning an complex type that holds a complex type this can cause an issue. The embedded complex types may need serialization defined for them. Or you can just remove the XML serializor which forces the response to be JSON instead of XML.

In the WebAPIConfig.cs Register method:

//Remove XML formatting 
config.Formatters.Remove(config.Formatters.XmlFormatter);
 

Some calls never get to the API

If you are seeing your calls in a cancelled state (Chrome inspector or fiddler) this means you are having CORS issues. This means the browser sees that you are trying to request data from the client side from a different domain. Keep in mind here that domain means different website. So just because you have test1.mysite.com  and test2.mysite.com (same domain different sub domain) it does not mean you are good. If those two sites are hosted in different webservers or different sites in IIS. Here are some sites with solutions on what you need to setup to make this work.

Web API, JavaScript, Chrome & Cross-Origin Resource Sharing

jQuery, CORS, JSON (without padding) and authentication issues

Using CORS to access ASP.NET services across domains

http://www.w3.org/TR/access-control/#origin-request-header

HTTP Cookies and Ajax requests over HTTPS

Here is an example AJAX call I setup that works.

var xhr = new XMLHttpRequest();
 
$.ajax( {
  method: "POST",
  url: form.attr( 'action' ),
  data: form.serialize(),
  xhrFields: {withCredentials: true},      
    cache: false,
    async:true,
  dataType: "application/x-www-form-urlencoded",
  success: function( response ) 
{
    console.log( response );
},
error: function (XMLHttpResponse, textStatus, errorThrown) {
            console.log(XMLHttpResponse);console.log(textStatus); console.log(errorThrown);
        }
 });

 

Passing Credentials and Cookies

Notice that I have xhrFields: {withCredentials: true}, this is a must have if you are doing an AJAX call that requires authentication. This will make sure any cookies created stay attached to the request.

We had to do authentication with Novell Access Manager (NetIQ Access Manager) and it was a serious pain. NetIQ really struggles to allow CORS calls. In fact I would say that it does not. Now I am no NAM expert and we were working with another firm who managed that, so if you know how to make it support CORS let me know. We ended up having to make it so CORS did not come into play.

There seems to be some confusion on the origin request header. You will even see this in some posts. Some people say to if you need to allow multiple headers just add it in one header separated by a comma. Others will say add multiple headers. Here is the key. If your request includes credentials you can only have one origin and no wildcards.

Per the w3 specs:

“If the resource supports credentials add a single Access-Control-Allow-Origin header, with the value of the Origin header as value, and add a single Access-Control-Allow-Credentials header with the case-sensitive string "true" as value.”

No comments: