假设我有一个 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
没有在上面的示例中返回。我如何获得包括嵌套组在内的所有组? 最佳答案
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
关于.net - 确定嵌套的 WindowsIdentity 实例组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4809460/