Say i have an instance of WindowsIdentity
and want to get groups it's a member of. I use the following code to obtain the list:
WindowsIdentity identity = null;
// get identity here
identity.Groups.Translate(typeof(NTAccount)).Select(x => x.Value);
i get something like this:
"BUILTIN\\Administrators"
"BUILTIN\\Users"
"NT AUTHORITY\\INTERACTIVE"
"CONSOLE LOGON"
I have a local group (say, MYSPECIALGROUP
) that has BUILTIN\\Administrators
as its member. MYSPECIALGROUP
is not returned in the sample above. How do i get all groups including the nested ones?
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
来源:https://stackoverflow.com/questions/4809460/determine-nested-groups-of-windowsidentity-instance