125

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?

Telarian
  • 789
  • 7
  • 23
chatura
  • 4,057
  • 4
  • 17
  • 19

4 Answers4

249

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" 
                        })
                );
}
GabrielBB
  • 1,809
  • 1
  • 21
  • 41
chatura
  • 4,057
  • 4
  • 17
  • 19
  • I've tried your example of HandleUnauthorizedRequest but when I specify the RouteValueDictionary, it just redirects to me a route that doesn't exist. It appends the route I want to redirect the user to to the route that the user wanted to access... si I get something like: localhost:9999/admin/Home when I wanted localhost:9999/Home – Marin Jul 15 '14 at 12:48
  • 1
    @Marin Try to add area = string.Empty in the RouteValueDictionary – Alex Dec 12 '14 at 13:45
  • 30
    I was upvoting but then i saw "if (condition) { return true; } else { return false; }" at the end.... – GabrielBB May 20 '16 at 18:48
  • @GabrielBB, I wish you would explain more. Does your comment mean I shouldn't follow this solution and that there's something you would change about it? What would you write in place of the if/else? Thank you. – Emil Oct 16 '17 at 18:15
  • 1
    @Emil I would just simply return the boolean that the String.Contains method gave me. But this is irrelevant, i didn't downvote, i just didn't upvote hehe. – GabrielBB Oct 17 '17 at 14:34
  • 2
    `.Name.ToString()` is redundant, since `Name` property is already string – FindOutIslamNow Apr 29 '18 at 13:55
  • For WebAPI implementation, a key difference is to use the System.Web.Http.Filters namespace and not the System.Web.Mvc. I also suggest inheriting from AuthorizationFilterAttribute. – Derek Wade May 07 '20 at 10:12
13

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }
Leonid Minkov
  • 141
  • 1
  • 5
4

Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _claim;

    public ClaimAuthorizeAttribute(string Claim)
    {
        _claim = Claim;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
        {
            return;
        }

        context.Result = new ForbidResult();
    }
}
RaphaelH
  • 1,894
  • 1
  • 27
  • 42
0

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}
Maurico Bello
  • 367
  • 2
  • 10