Query From LDAP for User Groups

Arslan Pervaiz picture Arslan Pervaiz · Mar 9, 2011 · Viewed 25.5k times · Source

How To Get User group of user from LDAP active directory in C# .NET for ASP. In my Scenario I want to Pass user name to method which query from LDAP Active directory and tell me my user is Member of This User Groups. Please help me in this

Answer

marc_s picture marc_s · Mar 9, 2011

If you're on .NET 3.5 or newer, you can also use the new System.DirectoryServices.AccountManagement (S.DS.AM) namespaces.

With this, you can do something like:

// create context for domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find the user
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, "YourUserName");

if(up != null)
{
    // get groups for that user
    var authGroups = up.GetAuthorizationGroups();
}

Read more about the new S.DS.AM namespace:

Managing Directory Security Principals in the .NET Framework 3.5