Provide a custom error page for 401 (failed authorization)
Asked Answered
W

1

1

I'm using Windows Authentication. The authentication works fine (the user is loaded with it's roles).

It's when authorization fails (using the Authorize) attribute that I want to provide a custom error page. It seems like the HandleError attribute only gets invoked for thrown exceptions but not for any error status codes (>= 300).

Custom errors section:

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

I got an ErrorController which returns views. But it do never get called.

Do I have to start throwing exceptions in a custom Authorize attribute to be able to handle 401, or is there a better MVC3 specific way?

Warwickshire answered 12/6, 2012 at 9:17 Comment(0)
N
3

You can override the HandleUnauthorizedRequest in your CustomAuthorize

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                                         {
                                             {"area", ""},
                                             {"controller", "Error"},
                                             {"action", "NotAuthorized"},
                                             {"returnUrl", filterContext.HttpContext.Request.RawUrl}
                                         });
}
Newberry answered 12/6, 2012 at 11:46 Comment(3)
Sure. But that handling get's implementation specific since it can't be extended. I rather stick with my current solution: blog.gauffin.org/2012/06/…Warwickshire
@Warwickshire I don't see any need for the exception since there isn't any code errors. you can redirect the user to your NotAuthorized Error page without exception so what is the point from throwing an exception ??Newberry
I mixed up your solution with another one which generated the entire result in the custom authorize attribute.Warwickshire

© 2022 - 2024 — McMap. All rights reserved.