2017年12月13日 星期三

c# csharp Connect Active Directory SSL using LdapConnection

// Get Ldap / ActiveDirectory Connection
private static LdapConnection GetLdapConn(
string certPath, string url, string user, string pass)
{
List<InputADUser> listInputADUser = new List<InputADUser>();
LdapConnection con = null;
try
{
System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2();
cert.Import(certPath); // your cert here, full path

con = new LdapConnection(url); // example: abc.com:636
con.Credential = new NetworkCredential(user, pass);
con.AuthType = AuthType.Ntlm;
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback((ldapcon, cer) =>
{
var cer2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(cer);

StringBuilder strb = new StringBuilder();

strb.AppendFormat("{0} {1} matches: {2}\n", "Subject", cert.Subject, cert.Subject.Equals(cer2.Subject));
strb.AppendFormat("{0} {1} matches: {2}\n", "Cert Hash", cert.GetCertHashString(), Enumerable.SequenceEqual<byte>(cer.GetCertHash(), cert.GetCertHash()));
strb.AppendFormat("{0} matches: {2}\n", "Public Key", cert.GetPublicKeyString(), Enumerable.SequenceEqual<byte>(cer.GetPublicKey(), cert.GetPublicKey()));
strb.AppendFormat("{0}: {1}, {2}", "Verification", cert.Verify(), cer2.Verify());

//Console.WriteLine(strb.ToString());
return true; // just return true is OK

});

con.Bind();
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return con;
}

// using LdapConnection to query records
public static void LdapSearch(
LdapConnection con,
string searchBase,
string searchFilter)
{
try
{

SearchRequest request = new SearchRequest(
searchBase,
searchFilter, // example (displayName=Peter)
System.DirectoryServices.Protocols.SearchScope.Subtree
);

PageResultRequestControl pageRequestControl = new PageResultRequestControl(100);

// used to retrieve the cookie to send for the subsequent request
PageResultResponseControl pageResponseControl;
request.Controls.Add(pageRequestControl);

SearchResponse response = (SearchResponse)con.SendRequest(request);

int cnt = 0;
while (true)
{
response = (SearchResponse)con.SendRequest(request);

SearchResultEntryCollection resultCollection = response.Entries;
for (int i = 0; i < resultCollection.Count; i++)
{
Console.WriteLine(resultCollection[i].DistinguishedName);
}

pageResponseControl = (PageResultResponseControl)response.Controls[0];
if (pageResponseControl.Cookie.Length == 0)
{
break;
}
pageRequestControl.Cookie = pageResponseControl.Cookie;
cnt++;
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}

}