Getting the Windows Groups of a User in .NET 2.0

by Dominick Baier

Related link: http://www.leastprivilege.com/GettingAllGroupsForAWindowsAccountInNET20.aspx



Given the complexity of today's Active Directory installations, the only safe way of getting all Windows groups a user is member of, is to inspect the token.


After you have acquired a token (e.g. though IIS authentication, LogonUser or Protocol Transition), wrap it in a WindowsIdentity and call:



List<string> getGroups(WindowsIdentity id)


{


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


  IdentityReferenceCollection irc = id.Groups;


 


  foreach (IdentityReference ir in irc)


  {


    NTAccount acc = (NTAccount)ir.Translate(typeof(NTAccount));


    groups.Add(acc.Value);


  }


 


  return groups;


}