方法上的多个授权属性

我在类方法上指定两个单独的Authorization属性时遇到问题:如果两个属性中的任何一个为true,则允许用户访问。

Athorization类看起来像这样:

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class AuthAttribute : AuthorizeAttribute { . . . 

和行动:

 [Auth(Roles = AuthRole.SuperAdministrator)] [Auth(Roles = AuthRole.Administrator, Module = ModuleID.SomeModule)] public ActionResult Index() { return View(GetIndexViewModel()); } 

有没有办法解决这个问题,还是需要重新考虑我的方法?

这将在MVC2中运行。

MVC处理多个AuthorizeAttribute实例,就好像它们是用AND 。 如果您想要OR行为,则需要实现自己的检查逻辑。 优选地,实现AuthAttribute以承担多个角色并使用OR逻辑执行自己的检查。

另一种解决方案是使用标准的AuthorizeAttribute并实现自定义IPrincipal ,它将实现bool IsInRole(string role)方法以提供“OR”行为。

这里有一个例子: https : //stackoverflow.com/a/10754108/449906

在更高版本的asp.net中有更好的方法可以在角色上同时执行OR和AND。 这是通过约定完成的,在单个Authorize中列出多个角色将执行OR,其中添加多个授权属性将执行AND。

或者例子

 [Authorize(Roles = "PowerUser,ControlPanelUser")] 

和例子

 [Authorize(Roles = "PowerUser")] [Authorize(Roles = "ControlPanelUser")] 

您可以在以下链接中找到更多相关信息:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles