Using MVC's AuthorizeAttribute with multiple groups of Roles?

[亡魂溺海] 提交于 2019-11-30 07:41:23

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.

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