有没有一种方法可以获取 Windows 认证用户所在的角色列表,而不是通过 WindowsPrincipal.IsInRole
方法进行显式检查?
有没有一种方法可以获取 Windows 认证用户所在的角色列表,而不是通过 WindowsPrincipal.IsInRole
方法进行显式检查?
WindowsPrincipal.IsInRole
仅检查用户是否是该名称组的成员; Windows组是角色。 您可以从WindowsIdentity.Groups
属性中获取用户是成员的组列表。
您可以从您的WindowsPrincipal
获取WindowsIdentity
:
WindowsIdentity identity = WindowsPrincipal.Identity as WindowsIdentity;
或者你可以从WindowsIdentity上的一个工厂方法获取它:
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsIdentity.Groups
是一个 IdentityReference
集合,它只提供组的 SID。如果您需要组名称,则需要将 IdentityReference
转换为 NTAccount
并获取其值:
var groupNames = from id in identity.Groups
select id.Translate(typeof(NTAccount)).Value;
编辑:Josh已经完成了! :)
试试这个
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) { }
}
<system.web>
...
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
...
</system.web>
Roles.GetRolesForUser()
来获取用户所属的所有Windows组。请确保您正在using System.Web.Security
。
var identity = User.Identity as WindowsIdentity;
。 - Jaider