In my last post I described some of my troubles working with Active directory entries from code. Here's another one which increased my baldness.
I described using a Directory search object, creating a DirectoryEntry out of that and setting the password to validate the entry. Like this:
const string MemberOf = "memberof";
DirectorySearcher ds = new DirectorySearcher();
ds.Filter = "samaccountname=" + userName;
ds.PropertiesToLoad.Add(MemberOf);
SearchResult sr = ds.FindOne();
DirectoryEntry adsEntry = sr.GetDirectoryEntry();
adsEntry.Password = passWord;
try
{
object o = adsEntry.NativeObject;
}
catch (DirectoryServicesCOMException ex)
{
// Not a valid account
}
Alas this does not always work in a real life domain. It does work when you are validating your own account under which you are logged in. But it does not work for any other account. What does work is creating a new directoryentry from scratch using exactly the same credentials.
DirectoryEntry adsEntry = new DirectoryEntry("", userName, passWord);
try
{
object o = adsEntry.NativeObject;
}
catch (DirectoryServicesCOMException ex)
{
// Not a valid account
}
Don't ask me why, without a doubt it's intended as security. Crossing the border from coding into the world of IT management just stays hard.