使用MVC的AuthorizeAttribute与角色的多组? [英] Using MVC's AuthorizeAttribute with multiple groups of Roles?
本文介绍了使用MVC的AuthorizeAttribute与角色的多组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要做的是一个行动处理器的双级角色检查。例如,要求用户在以下组中的至少一个:系统管理员,管理员和以下组中的至少一个:人力资源,薪酬,执行
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()
{
[...]
}
我需要的角色我自己的自定义属性采取基于role1和role2所或类似的东西?还是有更简单/更好的方式来做到这一点?
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
{
}
}
}
这篇关于使用MVC的AuthorizeAttribute与角色的多组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文