【问题标题】:Asp.net mvc Role based and Rule based operationsAsp.net mvc 基于角色和基于规则的操作
【发布时间】:2023-04-05 07:16:01
【问题描述】:

我对我的应用程序的角色和规则有点困惑。我的一些用户将获得授权编辑我网站上的数据。例如,我将创建这样的角色:

  • 编辑器
  • 管理员
  • 查看者

Asp.net mvc 有一个名为 Authorize 的属性。我可以为 controlleractions 指定角色。

    [Authorize]
    public class GeometryController : Controller
    {
        [Authorize(Roles = "VIEWER")]
        public ActionResult Get(string id)
        {
            return Content("OK.");
        }

        [HttpGet]
        [Authorize(Roles = "ADMIN, EDITOR")]
        public ActionResult Edit(string id)
        {           
           return Content("This operation is restricted for you.");   
        }
    }

但我还有另一个角色,一些用户可以通过工作区域编辑数据。例如

  • user1 只能编辑亚利桑那州数据和查看所有区域数据。
  • user2 可以编辑和删除德州数据。

【问题讨论】:

  • 只需扩展默认的Authorize 属性并包含您的逻辑

标签: asp.net asp.net-mvc security authorization


【解决方案1】:

我在我的代码中做了类似以下的事情。

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        private readonly string _feature;
        private readonly string _permission;

        public BRTAuthorizeAttribute( string feature, string permission)
        {
            _feature = feature;
            _permission = permission;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (!base.IsAuthorized(actionContext))
            {
                return false;
            }

            if(// check access rights)
            {
                return true
            }
            return false;
        }
    }

然后用[CustomAuthorize("feature", "permission")]装饰控制器,这应该是你需要的。

【讨论】: