2

Trying to figure out how to avoid requesting username and password when a controller action is called that has an Authorize header and simply redirect to a View.

In my web.config I have

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

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.

1 Answer 1

9

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)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new { controller = "Common", action = "AccessDenied" }));
        }
    }
}

[CustomAuthorize(Roles = "DOMAIN\\Group")]
public ActionResult Index()
{
   ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

DOH !! Being fairly new to .net and c#, I forgot all about custom validation classes. Worked like a charm
Authentication is different from Authorization

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.