确定WindowsIdentity实例的嵌套组

时间:2011-01-26 20:07:41

标签: .net windows security identity

假设我有一个WindowsIdentity的实例,并希望获得它所属的群组。我使用以下代码获取列表:

  WindowsIdentity identity = null;
  // get identity here
  identity.Groups.Translate(typeof(NTAccount)).Select(x => x.Value);

我得到这样的东西:

 "BUILTIN\\Administrators"
 "BUILTIN\\Users"
 "NT AUTHORITY\\INTERACTIVE"
 "CONSOLE LOGON"

我有一个以MYSPECIALGROUP为其成员的本地小组(例如,BUILTIN\\Administrators)。上面的示例中未返回MYSPECIALGROUP。我如何获得所有组,包括嵌套组?

1 个答案:

答案 0 :(得分:3)

Get a user's group memberships from Active Directory

正如该问题的答案所解释的那样,System.DirectoryServices.AccountManagement命名空间是您所需要的:

// get the user identity / roles
PrincipalContext pCtx = new PrincipalContext(ContextType.Domain, 
    Settings.Default.Domain,          // domain
    Settings.Default.DomainReadUser,  // user to access AD with 
    Settings.Default.DomainReadPass); // password of that user

UserPrincipal user = UserPrincipal.FindByIdentity(pCtx, 
    User.Identity.Name.Split('\\').Last()); // Windows Auth current user

// this will have all of the security groups, even nested ones
IEnumerable<Principal> userRoles = user.GetAuthorizationGroups();

由于您似乎在使用本地计算机用户/组,并且使用WindowsIdentity变量,因此您需要将前几行更改为:

PrincipalContext pCtx = new PrincipalContext(ContextType.Machine);
UserPrincipal user = UserPrincipal.FindByIdentity(pCtx, 
    identity.Name.Split('\\').Last());

另请参阅:Managing Directory Security Principals in the .NET Framework 3.5