2009-11-05 143 views
2

在調查表單授權/身份驗證時,我發現可以通過向FormsAuthenticationTicket添加角色數組來執行基於角色的授權。這樣,我可以寫基於角色/權限的表單授權/認證?

User.IsInRole(role from database) 

但是有什麼辦法做到像角色的權限相同的事情:

if (User.IsInRole(role from database)) { 
    if (User.CanRead()) { 
     //--- Let the user read 
    } 
    if (User.CanWrite()) { 
     //--- Let the user write 
    } 
} 

我讀了幾篇文章和論壇帖子的其中添加權限到陣列而不是角色,導致使用

User.IsInRole(permission from database) 

但是,這不是一回事。希望有人可以在這個問題上提供一些意見,或者鏈接到一篇文章或更好的代碼示例。

+0

爲什麼還原?不知道這與認證(標籤)有什麼關係,因爲User.CanRead和User.CanWrite都是授權方法。 http://www.duke.edu/~rob/kerberos/authvauth.html – mxmissile 2009-11-17 18:10:41

回答

4

你最好改變你對角色的看法。如果有幫助,使用術語「許可」或「聲明」。然後創建您需要的所有角色,並將給定的用戶鏈接到所有必要的角色。

一個用戶可以屬於多個角色。這樣,下面的簡單代碼就可以正常工作,並且不需要建立自己獨特的工作方式。

if(User.IsInRole(someRole) && User.IsInRole(someOtherRole)) 
{ 
    // do something 
} 

你可以做一些C#擴展方法,使這個更具可讀性太:

if(User.IsInSomeRoleAndOtherRole()) 
{ 
    // do something 
} 

擴展方法可以看起來像下面。用下面的代碼創建一個新類,然後在你的代碼中包含類命名空間,並且可以使用上面顯示的擴展方法。

using System.Security.Principal; 

namespace MyCompany 
{ 
    public static class MyExtensions 
    { 
    public static bool IsInSomeRoleAndOtherRole(this IPrincipal principal) 
    { 
     if (!principal.IsInRole("someRole")) 
     return false; 

     if (!principal.IsInRole("someOtherRole")) 
     return false; 

     return true; // the user meets the requirements 
    } 
    } 
} 
+0

+1是的,這很酷。 – griegs 2009-11-06 00:44:38

+0

好吧,我會這樣做的。你能告訴我如何製作擴展方法嗎? – 2009-11-06 06:43:40

+0

非常感謝; o) – 2009-11-08 10:26:43