Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and filter AD first & last name in ASP.NET

I am trying to search by AD username and display the First and Last Name to a table.

This is what I have so far:

DirectoryEntry myLDAPConnection = new DirectoryEntry("LDAP://company.com");
DirectorySearcher dSearch = new DirectorySearcher(myLDAPConnection);

I understand I need to do something with my dSearch object to filter what is returned, but I have no clue what to do beyond this.

like image 570
Johnrad Avatar asked Sep 17 '25 15:09

Johnrad


1 Answers

If 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
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }

    // find the group in question
    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

    // if found....
    if (group != null)
    {
       // iterate over members
       foreach (Principal p in group.GetMembers())
       {
           Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
           // do whatever you need to do to those members
       }
    }
}

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

like image 97
marc_s Avatar answered Sep 20 '25 03:09

marc_s