|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article explains how to authenticate a user over LDAPS using the BackgroundRecently, I ran into trouble using The Using the codeThe example uses a Also remember to omit the Connecting and authenticatingFirst, we set up our This example uses eDirectory's "contextless login" feature, so blank credentials are allowed. Depending on your LDAP server, you may need to specify credentials to search the directory. Also note that if no port is specified, then the default value of 389 will be used. LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(
"EDIRECTORYSERVER:636"));
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.VerifyServerCertificate =
new VerifyServerCertificateCallback(ServerCallback);
con.Credential = new NetworkCredential(String.Empty, String.Empty);
con.AuthType = AuthType.Basic;
Now we bind the initial connection. If using (con)
{
con.Bind();
The next step is to search for the user's fully qualified, distinguished name. This is a necessary step because when users provide their usernames, they don't provide the full context of their names in the directory; i.e. First, we prepare the SearchRequest request = new SearchRequest(
"o=LDAPRoot",
"(&(objectClass=Person)(uid=" + Login1.UserName + "))",
SearchScope.Subtree);
SearchResponse response = (SearchResponse)con.SendRequest(request);
If we get this far without an exception being thrown, we know that the root DN and search filter specified are valid. If either is invalid, a Now we can extract the DN from the search result. If you want to provide a "no such username" message, you can check that SearchResultEntry entry = response.Entries[0];
string dn = entry.DistinguishedName;
Now that we have the full DN for the user, we can check if the given password is valid. We set a new con.Credential = new NetworkCredential(dn, Login1.Password);
con.Bind();
}
If we get this far, we have successfully authenticated! We can now use a VerifyServerCertificateCallbackThis should need no explanation. We simply load the certificate file from disk and compare it to the certificate presented by the server. Production code should handle exceptions associated with reading the certificate: File not found, access denied, etc. If you really trust the server, you could omit all of this and just public static bool ServerCallback(
LdapConnection connection, X509Certificate certificate)
{
try
{
X509Certificate expectedCert =
X509Certificate.CreateFromCertFile(
"C:\\certificates\\certificate.cer");
if (expectedCert.Equals(certificate))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
History
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||