Connecting to an LDAP Server with .NET

I was recommended to use System.DirectoryServices.Protocols in order to be able to support connections to non-active Directoy LDAP servers here .
Unfortunately, I could not find the directory correctly. I would like to get a specific attribute for the user (e.g. mail ). This is easily done in the System.DirectoryServices namespace using the DirectorySearcher class. How can I achieve the same in the System.DirectoryServices.Protocols namespace. Here is what I still have:

 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 throws a DirectoryOperationException with the message The object does not exist .

I suspect something is wrong with my targetOu and ldapSearchFilter .

Thanks.

+3
source share
1 answer

I suspect that the main problem may be: samAccountName is strictly a Windows attribute that other LDAP servers are not aware of.

So, if you are going against LDAP without Active Directory, you should use something else to search - for example. sn (for last name or last name), givenName (first name), possibly displayName .

Another interesting option would be to use ANR queries (ambiguous name resolution) - see this page on SelfADSI around the middle where ANR explained.

With ANR, you should write your query as follows:

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

I also changed ObjectClass to ObjectCategory for two reasons:

  • ObjectCategory is unique, for example. contains only one value ( ObjectClass is multi-valued)
  • ObjectCategory usually indexed, and therefore the search is usually much faster using ObjectCategory

Does this return the results you are looking for?

+3
source

Source: https://habr.com/ru/post/1388910/


All Articles