views:

614

answers:

1

I'm attempting to authenticate a user against ADAM using a user I created in ADAM. However, regardless of the password used (correct, or incorrect), my search comes back with a valid DirectoryEntry object. I would assume that if the password is invalid, then the search would come back with a null object. Are my assumptions wrong or is there a flaw in the code below?

DirectoryEntry de = new DirectoryEntry("LDAP://localhost:389/cn=Groups,cn=XXX,cn=YYY,dc=ZZZ");
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user) (cn=" + userId + "))";
SearchResultCollection results = deSearch.FindAll();
if (results.Count > 0)
{
    DirectoryEntry d = new DirectoryEntry(results[0].Path, userId, password);
        if (d != null)
     DoSomething();

}
A: 

You need to access a property of the DirectoryEntry to determine if it's valid. I usually check if the Guid is null or not.

bool valid = false;
using (DirectoryEntry entry = new DirectoryEntry( results[0].Path, userId, password ))
{
     try
     {
         if (entry.Guid != null)
         {
            valid = true;
         }
     }
     catch (NullReferenceException) {}
}

Note: you'll also want to wrap your search root directory entry and searcher in using statements, or explicitly dispose of them when you are done so that you don't leave the resources in use.

P.S. I'm not sure exactly which exception gets thrown when you attempt to access an invalid directory entries properties. A bit of experimentation is probably in order to figure out which exception to catch. You won't want to catch all exceptions as there are other problems (directory server not available, for instance) that you may want to handle differently than a failed authentication.

tvanfosson
Great, thank you. That was very helpful. Now I'm running into a problem where I get an invalid user/password regardless of whether or not I enter the correct password. Any thoughts?
Does the user in ADAM have any rights to their own object? In Active Directory this is typically true, but I don't know about ADAM.
tvanfosson