1

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

[Authorize(Roles="editor")]

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

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

4

2 回答 2

3

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

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

[HttpPost]
[Authorize(Roles="editor")]    
[ValidateAntiForgeryToken]
public ActionResult Update(ArticleModel model)
{
   if(IsUserAllowedToUpdate(userId, model.ArticleId))
   {
      // Update article
   }
  return View(model);
}
于 2013-09-24T14:28:44.067 回答
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")]
于 2013-09-24T18:28:51.970 回答