Asp.net

ASP.NET MVC3 角色和權限管理 -> 使用執行時權限分配

  • September 2, 2011

ASP.NET MVC 允許使用者在設計時為功能(即操作)分配權限,就像這樣。

[Authorize(Roles = "Administrator,ContentEditor")]
public ActionResult Foo()
{
   return View();
}

要實際檢查權限,可以在(Razor)視圖中使用以下語句:

@if (User.IsInRole("ContentEditor"))
{
   <div>This will be visible only to users in the ContentEditor role.</div>
}

這種方法的問題是必須在設計時設置所有權限並將其分配為**屬性。(屬性是與 DLL 一起編譯的,因此我目前知道沒有機制可以在執行時應用屬性(以允許其他權限),例如 [Authorize(Roles = “Administrator,ContentEditor”)] 。

在我們的案例中,客戶端需要能夠在部署後更改哪些使用者擁有哪些權限。

例如,客戶端可能希望允許ContentEditor角色中的使用者編輯特定類型的某些內容。可能不允許使用者編輯查找表值,但現在客戶端希望允許此操作,而不授予使用者下一個更高角色的所有權限。相反,客戶端只是想修改使用者**目前角色可用的權限。

有哪些策略可用於允許在屬性之外(如在數據庫中)定義 MVC 控制器/視圖/操作的權限並在執行時評估和應用?

如果可能,我們非常希望盡可能地堅持使用 ASP.NET 成員資格和角色提供程序功能,以便我們可以繼續利用它提供的其他好處。

提前感謝您的任何想法或見解。

有哪些策略可用於允許在屬性之外(如在數據庫中)定義 MVC 控制器/視圖/操作的權限並在執行時評估和應用?

自定義 Authorize 屬性是實現此目的的一種可能性:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
       Roles = ... go ahead and fetch those roles dynamically from wherever they are stored
       return base.AuthorizeCore(httpContext);
   }
}

然後:

[MyAuthorize]
public ActionResult Foo()
{
   return View();
}

引用自:https://stackoverflow.com/questions/7286379