Wednesday, November 24, 2010

Authentication against Active Directory and ADAM

Today we were doing some work with authentication to see if we can improve the way it’s done on the external environments, Corp Website, Xtranet and the CEBs.  The plan was to use ADAM (Active Directory Application Mode) but this would mean a lot of nice features that are out-of-the-box with Active Directory.

To test both options I created a simple winform that will verify both options.

image

Using Active Directory

This is very well supported in the .Net Framework, you can use the built-in .Net references:
System.DirectoryServices.AccountManagement;
System.DirectoryServices;

Here is the code;

try

  // create a "principal context" - e.g. the domain (can also be a machine, too)
    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, txtDomain.Text))
    {
        // validate the credentials
        if (pc.ValidateCredentials(txtUsername.Text, txtPassword.Text))
            lblStatus.Text = "Login successful!";
        else
            lblStatus.Text = "Login unsuccessful!";
    }
}
catch (Exception ex)
{
    lblStatus.Text = ex.Message;
}

The PrincipleContext connects you to the domain, while the ValidateCredentials method will return True if its a valid name/password pair and false if not.

Using ADAM

This is not as well supported but it is there if needed.

try
{
     using (DirectoryEntry entry = new DirectoryEntry(txtPath.Text, txtUsername.Text, txtPassword.Text))
     {
         try
         {
             if (entry.Guid != null)
                 lblStatus.Text = "Login successful!";
             else
                 lblStatus.Text = "Login unsuccessful!";
         }
         catch (NullReferenceException ex)
         {
             lblStatus.Text = ex.Message;
         }
     }
}
catch (Exception ex)
{
     lblStatus.Text = ex.Message;
}

Here we create a Directory entry and connect to it using an LDAP path.  That is we tell the application where to find the Users information.  In my form I used; LDAP://localhost:389/cn=Groups,cn=XXX,cn=YYY,dc=ZZZ

The important thing here is that the address is entered in reverse order.  You enter the container for the User, then the container in which the User is located and ten any other container and so on until the top.

Someone might find it useful, but I’m happy to stick with Active Directory.