Query LDAP


Here is an example of how to query a secure LDAP service while using a certificate for authentication.  This example utilizes a previous blog for importing the certificate:  https://blogs.msdn.microsoft.com/metaverse/2017/11/09/capturing-a-pki-certificate/

char[] commaExcape = new char[] { ',' };
char quotestring = '"';
string accountName = "JDUser";
string url = "server.fqdn:636";
string attrs = "uid,givenname,cn,ou";
string[] attrset = attrs.Split(commaExcape);

X509SecurityToken certtoken = GetSecurityToken("a1b2c3");
X509Certificate2 cert = new X509Certificate2(certtoken.Certificate);
LdapConnection ldap = new LdapConnection(url);
ldap.SessionOptions.SecureSocketLayer = true;
ldap.SessionOptions.ProtocolVersion = 3;
ldap.AuthType = AuthType.Basic;
ldap.ClientCertificates.Add(cert);
ldap.Bind();
SearchRequest request = new SearchRequest("c=us", "uid=" + accountName, SearchScope.Subtree, attrset);
DirectoryResponse response = ldap.SendRequest(request);
try
{
SearchResultEntry entry = ((SearchResultEntry)((new ArrayList((ReadOnlyCollectionBase)(((SearchResponse)(response)).Entries)))[0]));
Hashtable hashtable = new Hashtable();
foreach(DictionaryEntry keyval in entry.Attributes)
{
ArrayList value = (new ArrayList((CollectionBase)(keyval.Value)));
var key = System.Text.Encoding.Default.GetString((byte[])value[0]).Replace(quotestring.ToString(), "");
hashtable.Add(keyval, key);
}
}
catch (ArgumentOutOfRangeException)
{

throw;
}

Comments (0)

Skip to main content