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?
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
{
}
}
}
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.
来源:https://stackoverflow.com/questions/6192475/using-mvcs-authorizeattribute-with-multiple-groups-of-roles