.Net MVC 4 using Windows Authentication - Redirecting an Unauthorized User

I have an MVC 4 intranet application that I created using Visual Studio 2012. I used WindowsAuthentication and it authenticates users as expected. In some activities, I restricted users to specific roles using the attribute Authorize. When a user clicks on a link that invokes a controller action for which the user does not have authorization, the "Authentication Required" dialog appears. When I log in with an account that does not have authorization, it continues to pop up a dialog. Instead, I would like to:

  • When the user does not have access to the page, you will open a dialog, as it is now.
  • When a user enters a login that is valid but not authorized to access the page, it redirects to another page, saying that access is denied.

How should I do it? As the relevant information, I configured the role provider using the discussed approach here

+4
source share
1 answer

To do this, you will need user authorization to independently handle unauthorized situations.

You will need a method like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
+2
source

All Articles