Determine nested groups of WindowsIdentity instance

梦想与她 提交于 2019-12-05 18:09:51
Adam Nofsinger

Get a user's group memberships from Active Directory

As the answer to that question explains, System.DirectoryServices.AccountManagement namespace is what you need:

// 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();

Since you seem to be doing local machine users/groups, and with your WindowsIdentity variable, you would want to change the first few lines to:

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

See also: Managing Directory Security Principals in the .NET Framework 3.5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!