在Web.config授权中需要多个角色

Der*_*son 8 asp.net authorization web-config roles

是否可以指定web.config文件的authorization元素中需要多个角色?我目前在我的网站的一个web.config中有一个特定目录的块:

<authorization>  
    <allow roles="Global, Region" />
    <deny users="*" />
</authorization>
Run Code Online (Sandbox Code Playgroud)

我刚刚确定了一个特殊情况,其中具有两个低于Global和Region的权限级别的人也应该有权访问此目录.粗略地说,我想要这样的事情:

<authorization>  
    <allow roles="GlobalManager, RegionManager, SiteManager && FooSite" />
    <deny users="*" />
</authorization>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我意识到我可能应该为这个场景找到一个新角色,但我想避免这种情况.谢谢!

eid*_*lon 3

我认为您无法通过 web.config 中允许的当前配置来做到这一点。不过,您可以执行如下操作...作为Page_Load相关页面的事件的第一行,请使用以下代码 (VB):

If Not (User.IsInRole("Role1") AndAlso User.IsInRole("Role2")) Then _
    FormsAuthentication.RedirectToLoginPage()
Run Code Online (Sandbox Code Playgroud)

当然,这行假设您正在使用 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 
Run Code Online (Sandbox Code Playgroud)

然后你可以将前面的代码写成更符合逻辑的内容,例如:

If Not (User.IsInRole("SiteManager") AndAlso User.ManagesSite(Request.Url.Host)) Then _
    FormsAuthentication.RedirectToLoginPage()
Run Code Online (Sandbox Code Playgroud)