3

What I want to do is a two-level role check on an action handler. For example, Require that the users is in at least one of the following groups: SysAdmins, Managers AND in at least one of the following groups: HR, Payroll, Executive.

Initial guess was that this might be the way to do this but I don't think it is:

[Authorize(Role="SysAdmins,Managers")]
[Authorize(Role="HR,Payroll,Executive")]
public ActionResult SomeAction()
{
    [...]
}

Do I need to role my own custom Attribute to take in Role1 and Role2 or something like that? Or is there an easier/better way to do this?

Jaxidian
  • 13,081
  • 8
  • 83
  • 125

2 Answers2

8

You'll need your own attribute. Here's mine:

public class AuthorizationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var portalModel = ContextCache<PortalModel>.Get(ContextCache.PortalModelSessionCache);

        var requestedController = filterContext.RouteData.GetRequiredString("controller");
        var requestedAction = filterContext.RouteData.GetRequiredString("action");

        var operation = string.Format("/{0}/{1}", requestedController, requestedAction);

        var authorizationService = IoC.Container.Resolve<IAuthorizationService>();

        if (!authorizationService.IsAllowed(AccountController.GetUserFromSession(), operation))
        {
            filterContext.Controller.ViewData["Message"] = string.Format("You are not authorized to perform operation: {0}", operation);
            filterContext.HttpContext.Response.Redirect("/Error/NoAccess");
        }
        else
        {
        }

    }

}
rboarman
  • 8,248
  • 8
  • 57
  • 87
  • FYI, I created my own attribute like you did but mine is very different than yours. For mine, I have two properties: `RoleRequirements` and `LicenseRequirements` and I essentially do an `IsInRole` check to see if either A) the collection is empty (no requirements) or B) the current user is in at least 1 role, for each collection. This works like a charm, and if I leave both empty then it simply requires the user to be logged in. I also created two other attributes, something like: `PublicAttribute` and `AnonymousOnlyAttribute`. This has all worked well. – Jaxidian Jun 02 '11 at 16:20
2

There is no built-in way to do what you want. You will either have to write your own new attribute, or add the check inside the action and return an UnauthorizedActionResult if the user's role fails your checks.

ventaur
  • 1,821
  • 11
  • 24