Keith Clark Keith Clark - 7 months ago 49
ASP.NET (C#) Question

How to display custom error if authorization fails in ASP.NET MVC

Trying to figure out how to avoid requesting username and password when a controller action is called that has an

header and simply redirect to a View.

In my web.config I have

<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" cacheRolesInCookie="false">
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
<authentication mode="Windows" />
<deny users="?" />

Then, in my controller, I am prefixing an action as follows

[Authorize(Roles = "DOMAIN\\Group")]
public ActionResult Index()
...controller action code here

If I set it to a DOMAIN\Group that I belong to, then the application works just as expected. If I change it to a bogus group for testing, I am presented with a username and password dialog. Obviously, authentication will never happen. If I click cancel in the dialog, I get redirected to the 401 error page.

What I would LIKE to do is, since by definition in the web.config file only windows users can connect, if that windows user is not in the chosen group, simply redirect to a particular View rather than prompting for a username and password.

Win Win

You can create a custom attribute and override HandleUnauthorizedRequest. Then you redirect to a custom page, if authorization fails,

public class CustomAuthorizeAttribute : AuthorizeAttribute
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new { controller = "Common", action = "AccessDenied" }));

[CustomAuthorize(Roles = "DOMAIN\\Group")]
public ActionResult Index()