LDAP Authentication From C#

Since we have LDAP server running, we might as well put it to use. Basic C# code is really straightforward:

using (var ldap = new LdapConnection(new LdapDirectoryIdentifier(this.HostName))) {
ldap.SessionOptions.ProtocolVersion = 3;

ldap.AuthType = AuthType.Anonymous;
ldap.Bind();
var dn = GetDn(ldap, userName);

ldap.AuthType = AuthType.Basic;
try {
ldap.Bind(new NetworkCredential(dn, password));
return GetUser(ldap, dn);
} catch (LdapException) {
return null;
}
}

First step is just simple anonymous bind to retrieve distinguished name based on user name. If our UID is jdoe, we simply search for uid=jdoe in dc=localdomain (base DN) using sub-tree search. That should give us location of our user wherever he is. Let's assume that user is now found at uid=jdoe,ou=People,dc=localdomain.

Full DN of user is then used together with password to authenticate ldap connection. If authentication fails our user cannot logon. If it works than another ldap search (uid=jdoe,ou=People,dc=localdomain) retrieves attributes, packs them into class and returns it back.

Sweet and simple.

P.S. Code in this post is just an excerpt. You can download full code here.

7 thoughts to “LDAP Authentication From C#”

  1. Nice, just the thing I was looking for!
    If you weren’t so far on the other side of the globe a round of beer would show my gratitude. For now it’s just:
    beersdue++;

  2. public bool ValidateUser(string userid, string password)
    {
    bool validation;
    try
    {
    LdapConnection ldc = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
    NetworkCredential ncon = new NetworkCredential(userid, password, “LDAP://religare.in:389”);
    ldc.Credential = ncon;
    ldc.AuthType = AuthType.Basic;
    ldc.Bind(ncon);
    validation = true;
    return validation;
    }
    catch (LdapException ldapException)
    {

    throw ldapException;

    }

    }

    1. You’ve got me confused. Explanation what are you trying to clarify/correct would be in order.
      It does not help to see (string)null.

Leave a Reply to Josip Medved Cancel reply

Your email address will not be published. Required fields are marked *