ASP.NET MVC3: Custom error for 401 Unauthorized

Have you tried to display a custom error message if authorization fails..

[Authorize(Roles="User")]
public class ItemController : Controller
{
}

.. by specifying it in the customErrors section in web.config:

    <customErrors defaultRedirect="~/Error/" mode="On">
      <error statusCode="404" redirect="~/Error/NotFound/" />
      <error redirect="~/Error/NotAuthorized/" statusCode="401" />
    </customErrors>

So have I, without getting it to work. The [HandleError] attribute cannot handle it either since it only handles exceptions (as the contract IExceptionFilter says).

Solution

public class BetterAuthorizeAttribute : AuthorizeAttribute
{
	protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
	{
		throw new NotAuthorizedHttpException(Roles);
	}
}

public class NotAuthorizedHttpException : HttpException
{
	public NotAuthorizedHttpException(string missingRoles)
		: base(401, string.Format("You do not have the required role(s) '{0}'.", string.Join(", ", missingRoles)))
	{
	}
}

That solution allows us to use the exception filter (HandleErrorAttribute) to serve the error page. Customization gets easier since we only have to make a change in global.asax to be able to serve any page. (i.e. switch the HandleError filter to our custom one).