April 1st 2010

Custom ASP.NET MVC Authorization Attribute For Ajax Requests

One issue that I have had for a while that I think I finally solved was what to do with unauthorized jQuery Ajax requests in my ASP.NET MVC application. I finally wrote a custom authorization attribute to take care of the situation.

I ran into two issues while constructing the attribute; the first was the need to send back different responses depending upon the content type of the request. The second was that the ASP.NET framework intercepts 401’s no matter what you do with your web config. You can see in the code below how I addressed these two issues.

Note: The idea to send a different status code is from a comment that Craig Stuntz made on this Stackoverflow post.

Then on the client side, my default jQuery Ajax setup has a check in the error handling to look for the 530 status code and if found it resets the window’s location as needed.

What would you do different or what did I not think of?