Share via


Get Groups for Current User

There are several ways of doing this but performance differs:

Method 1:

 WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();

foreach (var u in wi.Groups)
{
     Console.WriteLine("{0} ", u.Value);
}

Method 2:

 

 AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsIdentity wi = System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity;
 
foreach (var u in wi.Groups)
{
    Console.WriteLine("{0} ", u.Value);
}
 Method 3:
 using (var adContext = new PrincipalContext(ContextType.Domain, domainName))
{
      UserPrincipal user = UserPrincipal.Current;
      PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();
      foreach (var u in results)
      {
          Console.WriteLine("{0}", u.Sid);
      }
}
 
 Method 4:
 DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
string domainContext = rootDSE.Properties["defaultNamingContext"].Value as string;
string username = Environment.UserName;

List<string> userNestedMembership = new List<string>();

DirectoryEntry domainConnection = new DirectoryEntry();
domainConnection.Path = string.Format("LDAP://{0}", domainContext);
domainConnection.AuthenticationType = AuthenticationTypes.Secure;

DirectorySearcher samSearcher = new DirectorySearcher();

samSearcher.SearchRoot = domainConnection;
samSearcher.Filter = "(samAccountName=" + username + ")";

SearchResult samResult = samSearcher.FindOne();

if (samResult != null)
{
    DirectoryEntry theUser = samResult.GetDirectoryEntry();
    theUser.RefreshCache(new string[] { "tokenGroups" });

    foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
    {
        System.Security.Principal.SecurityIdentifier mySID = new System.Security.Principal.SecurityIdentifier(resultBytes, 0);
        Console.WriteLine(mySID);
    }
}