Asp.net

在 Web.config 授權中需要多個角色

  • June 22, 2012

是否可以在 web.config 文件的授權元素中指定需要多個角色?我目前在我的網站的一個 web.config 中有這個塊,用於特定目錄:

<authorization>  
   <allow roles="Global, Region" />
   <deny users="*" />
</authorization>

我剛剛確定了一種特殊情況,即擁有兩個比 Global 和 Region 更低級別權限的人也應該有權訪問此目錄。粗略地說,我想要這樣的東西:

<authorization>  
   <allow roles="GlobalManager, RegionManager, SiteManager && FooSite" />
   <deny users="*" />
</authorization>

有任何想法嗎?我意識到我可能應該為這種情況扮演一個新角色,但我想避免這種情況。謝謝!

我不認為你可以通過 web.config 中允許的目前配置來做到這一點。但是,您可以執行以下操作…作為相關Page_Load頁面事件的第一行,請使用以下程式碼(VB):

If Not (User.IsInRole("Role1") AndAlso User.IsInRole("Role2")) Then _
   FormsAuthentication.RedirectToLoginPage()

這行當然是假設您正在使用 FormsAuthentication。如果不是,您需要FormsAuthentication.RedirectToLoginPage()根據您的身份驗證方法替換為適當的程式碼。

我不完全了解您的情況,但根據您的程式碼,您似乎可以更進一步,添加一個包含使用者到站點映射的表,然後執行以下操作:

在公共模組中,添加以下程式碼:

<System.Runtime.CompilerServices.Extension()> _
Public Function ManagesSite(target As System.Security.Principal.IPrincipal, siteName As String) As Boolean
   Return [ code here to look up whether this user can access the site specified ]
End Function 

然後你可以把前面的程式碼寫成更合乎邏輯的東西,比如:

If Not (User.IsInRole("SiteManager") AndAlso User.ManagesSite(Request.Url.Host)) Then _
   FormsAuthentication.RedirectToLoginPage()

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