How to query ActiveDirectory using LDAP with username, not CN?

If I installed the .NET DirectoryEntry.Path on something like:

LDAP://CN=John Smith,OU=Group Name,DC=example,DC=com 

Everything works fine, and I get the DirectoryEntry I need. However, I do not know the true common username (CN). I only know their username, "John.Smith".

So how can I request a username? I tried all of the following without success:

 LDAP://CN=John.Smith,OU=Group Name,DC=example,DC=com LDAP://sAMAccountName=John.Smith,OU=Group Name,DC=example,DC=com LDAP://userPrincipalName=John.Smith,OU=Group Name,DC=example,DC=com LDAP:// userPrincipalName=John.Smith@example.com ,OU=Group Name,DC=example,DC=com LDAP://uid=John.Smith,OU=Group Name,DC=example,DC=com LDAP://o=John.Smith,OU=Group Name,DC=example,DC=com 
+4
source share
1 answer

You cannot simply query by creating an LDAP string - you will need to use the code for this.

Sort of:

 DirectoryEntry deRoot = new DirectoryEntry("LDAP://yourserver/CN=Users,dc=YourCompany,dc=com"); DirectorySearcher dsFindUser = new DirectorySearcher(deRoot); dsFindUser.SearchScope = SearchScope.SubTree; dsFindUser.PropertiesToLoad.Add("sn"); // surname = last name dsFindUser.PropertiesToLoad.Add("givenName"); // first name dsFindUser.Filter = string.Format("(&(objectCategory=Person)(anr={0}))", yourUserName); SearchResult rseult = dsFindUser.FindOne(); if(result != null) { if(result.Properties["sn"] != null) { string lastName = result.Properties["sn"][0].ToString(); } if(result.Properties["givenName"] != null) { string lastName = result.Properties["givenName"][0].ToString(); } } 

Full MSDN documentation in the System.DirectoryServices.DirectorySearcher class can be found on MSDN - it has many additional properties and settings.

If you're on .NET 3.5, things got a lot easier with a strongly typed library of routines for handling users and groups - see this excellent MSDN Article on this topic for more information.

Hope this helps

Mark

+9
source

All Articles