ASP.NET MVC4授权取决于角色和信息

时间:2013-09-24 13:41:07

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

我目前正在开发一个ASP.NET MVC4应用程序,它有3个角色:admin,manager和editor。编辑可以在系统中使用CRUD文章,但编辑只能阅读,更新或删除他们的OWN文章。我已经看到我可以通过添加:

来控制对控制器和操作的访问
[Authorize(Roles="editor")]

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

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

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

您可以在系统核心中实现此功能,例如在数据存储区中添加字段,识别创建者和具有权限的用户。

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

public class 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")]
相关问题