2011-01-26 47 views
3

假设我有一个WindowsIdentity的实例,并且想获得它所属的组。我用下面的代码来获取列表:确定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" 

我有了BUILTIN\\Administrators作为其成员的本地组(比如说,MYSPECIALGROUP)。上述示例中未返回MYSPECIALGROUP。我如何获得全部组包括嵌套组?

回答

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