Search code examples
asp.net-mvc-4authorizationcustom-attributes

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)


I need to control the access to views based on users privilege levels (there are no roles, only privilege levels for CRUD operation levels assigned to users) in my MVC 4 application.

As an example; below the AuthorizeUser will be my custom attribute and I need to use it like this:

[AuthorizeUser(AccessLevels="Read Invoice, Update Invoice")]
public ActionResult UpdateInvoice(int invoiceId)
{
   // some code...
   return View();
}


[AuthorizeUser(AccessLevels="Create Invoice")]
public ActionResult CreateNewInvoice()
{
  // some code...
  return View();
}


[AuthorizeUser(AccessLevels="Delete Invoice")]
public ActionResult DeleteInvoice(int invoiceId)
{
  // some code...
  return View();
}

Is it possible to do it this way?


Solution

  • I could do this with a custom attribute as follows.

    [AuthorizeUser(AccessLevel = "Create")]
    public ActionResult CreateNewInvoice()
    {
        //...
        return View();
    }
    

    Custom Attribute class as follows.

    public class AuthorizeUserAttribute : AuthorizeAttribute
    {
        // Custom property
        public string AccessLevel { get; set; }
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {                
                return false;
            }
    
            string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB
    
            return privilegeLevels.Contains(this.AccessLevel);           
        }
    }
    

    You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary(
                        new
                            { 
                                controller = "Error", 
                                action = "Unauthorised" 
                            })
                    );
    }