Reputation: 300
I have requirement to search for users in a LDAP directory using C#. I can do it using DirectoryEntry
and DirectorySearcher
as shown in code below:
SearchResultCollection sResults = null;
DirectoryEntry dEntry = new DirectoryEntry(_LDAPConnectionString);
DirectorySearcher dSearcher = new DirectorySearcher(dEntry);
dSearcher.Filter = String.Format("(&(objectClass=user)(cn={0}))", userName);
sResults = dSearcher.FindAll();
But the requirement is to create a LdapConnection
object using a standard access user (always the same) as shown below. And use that particular LdapConnectionObject
to search users using username.
LdapConnection ldapConnectionObject = new LdapConnection(
new LdapDirectoryIdentifier(_hostName, _port),
null,
AuthType.Basic);
ldapConnectionObject.Bind(accessUserCredential);
How do I use the above ldapConnectionObject
to search for users?
Upvotes: 4
Views: 24255
Reputation: 300
I found the answer searching using LdapConnection object. So we can use the SendRequest method of the LdapConnection class using the SearchRequest to get search response back. In below example, I have searched the user with uid userName and retreived its DN.
ldapConnection = new LdapConnection(
new LdapDirectoryIdentifier(_hostName, _port),
null,
AuthType.Basic
);
string searchFilter = String.Format("(&(objectClass=user)(uid={0}))", userName);
string userStore = "OU=WebsiteUsers,OU=InternalUsers";
SearchRequest searchRequest = new SearchRequest
(userStore,
searchFilter,
System.DirectoryServices.Protocols.SearchScope.Subtree,
new string[] { "DistinguishedName" });
var response = (SearchResponse)ldapConnection.SendRequest(searchRequest);
string userDN = response.Entries[0].Attributes["DistinguishedName"][0].ToString();
Upvotes: 9