ASP.NET MVC ActionFilters and Response.Redirect

Posted by Jason on December 19, 2008 at 5:28 pm

There is an issue with using the following code in an action filter:

  1. filterContext.HttpContext.Response.Redirect(loginUrl, true);

which is a bit of code quite common in an authentication filter. The problem is it will throw a ThreadAbortException as soon as you put your code on a live site resulting in the error page for anyone who is not logged in. This is probably not what you want since you are attempting to redirect them to the login page.

Now it is a little unfair to say that it’s an issue because that is the intended functionality. But it doesn’t fit well with MVC controllers, especially since Microsoft’s official suggestion is to set the endResponse flag to false. That is just downright misleading since your controller action (which the filter just decided you can’t access) is still executed after the filter fails authentication – resulting in the action code being executed anyway whilst you see the login screen on the browser and assume it all went swimmingly! Meanwhile those files that this user shouldn’t have access to got deleted.

Yeah, that’s what I just did during testing whilst proving to myself that you can’t fake the URL as a non-registered user. Imagine my surprise. It’s true that the chances of a malicious user actually working out the URL might be low, but that’s no reason to leave the door open.

Oh, and your unit tests probably won’t catch this because the filters don’t get executed by the unit tests. But I digress…

To cut a long story short, this bit of code in your base controller (assuming you have one, otherwise stick in in all of the controllers) will prevent the issue:

  1. protected override void OnException(ExceptionContext filterContext)
  2. {
  3.     if (filterContext.Exception is ThreadAbortException)
  4.     {
  5.         filterContext.ExceptionHandled = true;
  6.     }
  7. }

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment