Using MVC's AuthorizeAttribute with multiple groups of Roles?

我与影子孤独终老i 提交于 2019-11-29 10:59:13

问题


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?


回答1:


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
        {
        }

    }

}



回答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.



来源:https://stackoverflow.com/questions/6192475/using-mvcs-authorizeattribute-with-multiple-groups-of-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!