Using MVC's AuthorizeAttribute with multiple groups of Roles?
asp.net-mvc, asp.net-mvc-2, authentication, authorization
Solution
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
{
}
}
}
Problem
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?