See if user is part of Active Directory group in C# + Asp.net

mike_h picture mike_h · Feb 3, 2010 · Viewed 85.7k times · Source

I need a way to see if a user is part of an active directory group from my .Net 3.5 asp.net c# application.

I am using the standard ldap authentication example off of msdn but I don't really see how to check against a group.

Answer

Nick Craver picture Nick Craver · Feb 3, 2010

With 3.5 and System.DirectoryServices.AccountManagement this is a bit cleaner:

public List<string> GetGroupNames(string userName)
{
  var pc = new PrincipalContext(ContextType.Domain);
  var src = UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc);
  var result = new List<string>();
  src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
  return result;
}