Search code examples
c#asp.netactive-directoryldap-queryusergroups

Querying LDAP for Usergroup of Specific User


I have to check usergroups of LDAP Active Directory for a specific user in C#. Mean I pass this username to a method and it returns me list of group from that user belongs. Can You Please help me in this. Im Searching alot But Everytime get new error.

LDAP Path: 192.168.1.4

Domain Name: Arslan

UserName: ArslanP

Password: testad


Solution

  • Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

    Managing Directory Security Principals in the .NET Framework 3.5

    Basically, add a reference to the assembly System.DirectoryServices.AccountManagement, and then you can define a domain context and easily find users and/or groups in AD:

    using System.DirectoryServices.AccountManagement;
    
    public List<GroupPrincipal> GetGroupsForUser(string username)
    {
      List<GroupPrincipal> result = new List<GroupPrincipal>();
    
      // set up domain context - if you do a lot of requests, you might
      // want to create that outside the method and pass it in as a parameter
      PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
      // find user by name
      UserPrincipal user = UserPrincipal.FindByIdentity(username);
    
      // get the user's groups
      if(user != null)
      {
         foreach(GroupPrincipal gp in user.GetAuthorizationGroups())
         {
             result.Add(gp);
         }    
      }
    
      return result;
    }
    

    The new S.DS.AM makes it really easy to play around with users and groups in AD: