Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to LDAP Server from .NET

I've been recommended to use System.DirectoryServices.Protocols to be able to support connecting to LDAP servers other than Active Directoy here.
Unfortunately, I have not been able to search the directory properly. I'd like to be able to get a certain attribute for a user (e.g. mail). This is easily done in System.DirectoryServices namespace by using DirectorySearcher class. How can I achieve the same in System.DirectoryServices.Protocols namespace. Here's what I have so far:

var domainParts = domain.Split('.');
string targetOu = string.Format("cn=builtin,dc={0},dc={1}", domainParts[0], domainParts[1]);
string ldapSearchFilter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);

// establish a connection to the directory
LdapConnection connection = new LdapConnection(
                                new LdapDirectoryIdentifier(domain),
                                new NetworkCredential() { UserName = username, 
                                                   Password = "MyPassword" });
SearchRequest searchRequest = new SearchRequest(
                targetOu, ldapSearchFilter, SearchScope.OneLevel, new[] {"mail"});

This code raises exception of type DirectoryOperationException with message The object does not exist.

I suspect there's something wrong with my targetOu and ldapSearchFilter variables.

Thanks.

like image 897
Kamyar Avatar asked Jan 23 '26 12:01

Kamyar


1 Answers

I suspect the main problem might be: samAccountName is a strictly Windows-only attribute that other LDAP servers won't know about.

So if you're going against a non-Active Directory LDAP, you should use something else for searching - e.g. sn (for surname or last name), givenName (first name), possibly displayName.

Another interesting option might be to use ANR (ambiguous name resolution) searches - see this page on SelfADSI roughly in the middle, where ANR is explained.

With ANR, you would write your query like this:

string ldapSearchFilter = 
   string.Format("(&(ObjectCategory={0})(anr={1}))", "person", username);

I also changed ObjectClass to ObjectCategory for two reasons:

  • ObjectCategory is single-valued, e.g. only contains a single value (ObjectClass is multi-valued)
  • ObjectCategory is typically indexed, and thus searches are typically a lot faster using ObjectCategory

Does this return the results you're looking for?

like image 138
marc_s Avatar answered Jan 26 '26 01:01

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!