2013-09-24 24 views
1

我目前正在開發一個ASP.NET MVC4應用程序,它有3個角色:admin,manager和editor。編輯者可以在系統中添加CRUD文章,但編輯者只能閱讀,更新或刪除他們自己的文章。我見過我可以通過添加控制訪問控制器和動作:ASP.NET MVC4授權取決於角色和信息

[Authorize(Roles="editor")] 

,但只限製作用不是信息。

如果編輯器A只創建了文章1,編輯器A就可以訪問該文章。 沒有其他角色可以訪問控制器或信息。 爲了限制角色和上下文的訪問,最佳實踐是什麼?

回答

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")] 
裝點你的控制器
3

創建自定義AuthorizeAttribute來檢查是否允許用戶更新特定文章是不實際的。

而是想要檢查控制器(或業務邏輯)中的邏輯。你可以在很多開源項目中看到這種方法。

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