ASP.NET - Redirect to Error Page if Roles Authorization Fails

19,759

Solution 1

A custom authorize attribute overriding the HandleUnauthorizedRequest method could do the job:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // The user is not authenticated
            base.HandleUnauthorizedRequest(filterContext);
        }
        else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            // The user is not in any of the listed roles => 
            // show the unauthorized view
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/Unauthorized.cshtml"
            };
        }
        else
        { 
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

and then:

[MyAuthorize(Roles = "developer")]
public ActionResult Develop()
{
    ...
}

Solution 2

You can also do this with custom error page for 401 status codes.

See this question for implementation details.

Solution 3

You can use it like this.Because if you dont have authority it comes method. Authorization control is not necessary

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // The user is not authenticated
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/Unauthorized.cshtml",
            };
        }
    }
Share:
19,759

Related videos on Youtube

Brandon
Author by

Brandon

I write the code that makes the ladies scream.

Updated on June 05, 2022

Comments

  • Brandon
    Brandon almost 2 years

    I am using MVC 3 with Forms Authentication. On my controller or methods, I am doing the following:

    [Authorize (Roles = "developer")]
    

    In this situation, I want to check if the user is logged in and if not, return them to the login page. However, if the 'IsInRole' check for that user returns false, I want them to go to a different view that says something like 'Not authorized'.

    What is the best way to accomplish something like this? I was hoping to avoid creating a new Authorization attribute so I didn't have to refactor every Authorize attribute in my entire application, but if that is what is required, I will go that route.

  • Ricker Silva
    Ricker Silva about 10 years
    Where do you put this custom implementation?
  • Vijay Chavda
    Vijay Chavda over 7 years
    @darin-dimitrov Where should we keep the custom implementations, is there a convention/recommendation?