0
votes

What is the best LDAP filter to search for users in Active Directory? In my example filters I also exclude disabled accounts and accounts without email addresses.

Consider searching for the following name: "firname middlename lastname". My code parses this name as the following:

$name = "firstname middlename lastname";
$nameArray = explode(" ", $name);
$fullName = $name;
$firsName = $nameArray[0];
$lastName = $nameArray[count($nameArray)-1];

This filter works great if you only search for "firstname lastname" or "firstname middlename lastname", but dont work if you search for "firstname middlename":

(&(!(userAccountControl:1.2.840.113556.1.4.803:=2))(mail=*)(givenname=$firstName*)(sn=$lastName*))

This filter works as intended but is painfully slow:

(&(!(userAccountControl:1.2.840.113556.1.4.803:=2))(mail=*)(|(&(givenname=$firstName*)(sn=$lastName*))(displayName=*$fullName*)))

The displayName holds off course the full name, but is formatted "lastname firstname middlename". In a perfect world, people would have 0 or 1 middle names, or only one lastname, but off course they can have more than that.

Any suggestions how to make a good (fast) search filter?

1

1 Answers

1
votes

When doing Active Directory searches via LDAP, AD looks at your search query and starts selecting items from the database from the leftmost filter. In your queries, you first select all non-disabled accounts and only afterwards you look for the values you got from the user.

My suggestion is to build the search query so that you start with the most accurate information you got from your user, i.e.:
User entered: Robert ross -> your query would start with (givenName=$gn*).

In other words, the first condition should be the one that is most restrictive, meaning there will be less objects which will meet the criteria.

Also, you can limit the amount of objects returned from the server to a smaller number than the default (usually 1000) and only ask for more results when the user demands them. Also, sorting is quite expensive for the AD server so if you really need to sort, consider sorting with PHP.

For a very detailed reading on optimising AD search operations, refer to Microsoft's MSDN page dedicated to this topic.