【发布时间】:2010-10-20 05:17:37
【问题描述】:
有没有办法在不通过WindowsPrincipal.IsInRole 方法显式检查的情况下获取 Windows 身份验证用户所在的角色列表?
【问题讨论】:
标签: .net windows-identity rbac windows-principal
有没有办法在不通过WindowsPrincipal.IsInRole 方法显式检查的情况下获取 Windows 身份验证用户所在的角色列表?
【问题讨论】:
标签: .net windows-identity rbac windows-principal
WindowsPrincipal.IsInRole 只检查用户是否是具有该名称的组的成员; Windows 组是一个角色。您可以从WindowsIdentity.Groups 属性中获取用户所属组的列表。
您可以从您的WindowsPrincipal 获得WindowsIdentity:
WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
或者您可以从 WindowsIdentity 上的工厂方法获取它:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsIdenity.Groups 是IdentityReference 的集合,它只为您提供组的 SID。如果您需要组名,您需要将IdentityReference 转换为NTAccount 并获取值:
var groupNames = from id in identity.Groups
select id.Translate(typeof(NTAccount)).Value;
【讨论】:
var identity = User.Identity as WindowsIdentity;
编辑:乔什打败了我! :)
试试这个
using System;
using System.Security.Principal;
namespace ConsoleApplication5
{
internal class Program
{
private static void Main(string[] args)
{
var identity = WindowsIdentity.GetCurrent();
foreach (var groupId in identity.Groups)
{
var group = groupId.Translate(typeof (NTAccount));
Console.WriteLine(group);
}
}
}
}
【讨论】:
如果没有连接到域服务器,Translate函数可能会抛出以下异常The trust relationship between this workstation and the primary domain failed.
但是对于大多数组来说,都可以,所以我使用:
foreach(var s in WindowsIdentity.GetCurrent().Groups) {
try {
IdentityReference grp = s.Translate(typeof (NTAccount));
groups.Add(grp.Value);
}
catch(Exception) { }
}
【讨论】:
在 ASP.NET MVC 站点中,您可以这样做:
将此添加到您的 Web.config:
<system.web>
...
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
...
</system.web>
然后您可以使用Roles.GetRolesForUser() 获取用户所属的所有Windows 组。确保你是using System.Web.Security。
【讨论】: