C# LDAP Client

So, one of our related departments has information available to us, specifically, "user email" when given "user alternate ID". It's in an LDAP server, so I had a chance to play with using LDAP as a subset of C#'s Active Directory libraries. This was used for a one-time script, so I haven't fully cleaned it up, but figured it might help at some point to put it here as a quick sample.

using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Net;
using System.Security.Cryptography.X509Certificates;

public string GetEmailFromLDAP(string altId)
{
const string server = "ldap.somehost.com";
const int port = 636;
const bool fullyQualifiedHostname = true;
const bool tcp = false;
const string username = "uid=hr,o=departmentaccounts";
const string password = 12345";
const string baseDN = "ou=people,dc=somehost,dc=com";
string ldapSearchFilter = "(altId=" + altId + ")";
string attributeName = "email";

LdapDirectoryIdentifier id = new LdapDirectoryIdentifier(server, port, fullyQualifiedHostname, tcp);
LdapConnection conn = new LdapConnection(id);
conn.SessionOptions.SecureSocketLayer = true;
conn.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(ServerCallback);
conn.SessionOptions.QueryClientCertificate = new QueryClientCertificateCallback(ClientCallback);
conn.AuthType = AuthType.Basic;
conn.Credential = new NetworkCredential(username, password);
conn.Bind();

string[] attributesToReturn = { attributeName };
SearchRequest request = new SearchRequest(baseDN, ldapSearchFilter, System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn);


SearchResponse response = (SearchResponse)conn.SendRequest(request);
if (response.Entries.Count > 1)
{
throw new Exception("Multiple results in LDAP directory for single EDIPI.");
}
SearchResultEntry entry = response.Entries[0];
DirectoryAttribute attribute = entry.Attributes[attributeName];

conn.Dispose();

return (string)attribute[0];

}
private static bool ServerCallback(LdapConnection conn, X509Certificate cert)
{
return true;
}
private static X509Certificate ClientCallback(LdapConnection conn, byte[][] trustedCAs)
{
return null;
}

2 comments:

Unknown said...

Hi, have you noticed any memory leaks with QueryClientCertificateCallback?

I want to use it but wary after reading this:

www.joekaplan.net/JoeRichardsFindLDAPClientAPIBugThatAffectsSDSProtocols.aspx

thanks!

Unknown said...

I opened a ticket with MS Support, they confirmed the leak and that it's fixed in Windows 7 and Windows 2008 R2.

-Bruce Krasnof
Tufts U.