Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Like search in ActiveDirectory

I am searching LDAP using the following code in C# to poll active directory for users:

DirectoryEntry entry = new DirectoryEntry(ldapPath, userName, password);

DirectorySearcher Searcher = new DirectorySearcher(entry);

Searcher.CacheResults = true;
Searcher.SearchScope = SearchScope.Subtree;

Searcher.Filter = "(&(&(objectCategory=person)(objectClass=user))
    (|(samaccountname=" + userSearch.SamAccountName + "*)
    (&(GivenName=" + userSearch.FirstName + "*)(SN=" + userSearch.Surname + 
        "*))))";

Searcher.PropertiesToLoad.AddRange(new string[] {"DisplayName", "GivenName",
    "DistinguishedName","Title","manager",
         "mail", "physicalDeliveryOfficeName", "DirectReports", "Company", 
         "Description", "SAMAccountName"});

SearchResultCollection results = Searcher.FindAll();

List<ActiveUser> activeUsers = new List<ActiveUser>();

I ran it with the input parameters userSearch.FirstName = "jo" and userSearch.LastName = "bl" and was expecting one user "Joe Bloggs", but this didn't appear in the result list. If I try this using the name textbox in Active Directory Users and Computers tool in Windows, Joe Bloggs appears as the only user in the list. I am using the correct LDAP path. Am I using the wrong filter to replicate the functionality in the windows tool? Is there a 'like' search on display name?

Any help would be appreciated.

like image 504
Sico Avatar asked Nov 28 '11 13:11

Sico


1 Answers

If you're on .NET 3.5 or up, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

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

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) of "Bruce"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Jo*";
qbeUser.Surname = "Bl*";

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement

like image 129
marc_s Avatar answered Sep 21 '22 20:09

marc_s