【问题标题】:ASP.NET MVC4 authorization depending on role and informationASP.NET MVC4 授权取决于角色和信息
【发布时间】:2013-09-29 18:26:37
【问题描述】:

我目前正在开发一个 ASP.NET MVC4 应用程序,它有 3 个角色:管理员、经理和编辑。编辑可以在系统中对文章进行 CRUD,但编辑只能阅读、更新或删除他们的 OWN 文章。我已经看到我可以通过添加来控制对控制器和操作的访问:

[Authorize(Roles="editor")]

但它只限制角色而不是信息。

如果编辑 A 创建了文章 1 只有编辑 A 可以访问该文章。 没有其他角色可以访问控制器或信息。 为了按角色和上下文限制访问,最佳实践是什么?

【问题讨论】:

    标签: asp.net asp.net-mvc-4 authentication authorization


    【解决方案1】:

    您可以在系统的核心中实现这一点,例如通过在数据存储中设置一个字段,识别创建者和具有权限的用户。

    然后你可以实现你自己的授权属性;

    公共类 CustomAuthenticateAttribute : AuthorizeAttribute {

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // your own business logic, for instance, check if the user is the 
        // creator of the requested resource (check a database field you 
        // have created to identify the creator etc...)
        // if that goes well authorize using regular roles, below
    
        return base.AuthorizeCore(httpContext);
    }
    

    }

    然后你可以用

    装饰你的控制器
    [AuthorizeAttribute(Role = "editors")]
    

    【讨论】:

      【解决方案2】:

      创建自定义AuthorizeAttribute 来检查是否允许用户更新特定文章是不切实际的。

      相反,您想在控制器(或业务逻辑)中检查该逻辑。您可以在很多开源项目中看到这种方法。

      [HttpPost]
      [Authorize(Roles="editor")]    
      [ValidateAntiForgeryToken]
      public ActionResult Update(ArticleModel model)
      {
         if(IsUserAllowedToUpdate(userId, model.ArticleId))
         {
            // Update article
         }
        return View(model);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        • 1970-01-01
        • 2010-10-21
        • 1970-01-01
        • 2020-05-18
        • 2013-02-13
        • 1970-01-01
        相关资源
        最近更新 更多