Oct 062012
 

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 Responses to “LDAP authentication from C#”

Comments (7)
  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. Second for the beers comment! Amazing chunk of code.

  3. 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;

    }

    }

  4. Thanks for providing the code that is functional :-)). Great work.

  5. This works, Great.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>