In the following code,
private bool AuthenticateUser(string userName, string password)
{
try
{
using(var entry = new DirectoryEntry("myLDAP", userName, password))
{
// Attempt to bind to the directory entry
object nativeObject = entry.NativeObject;
return true; // Authentication succeeded
}
}
catch(DirectoryServicesCOMException)
{
// Handle exception for failed authentication
return false;
}
catch(Exception ex)
{
// Handle other exceptions (logging, etc.)
MessageBoxes.msgBoxOK(
"Authentication Error",
$"An error occurred: {ex.Message}",
MessageBoxImage.Error);
return false;
}
}
I am getting a,
'System.DirectoryServices.DirectyEntry.NativeObject.get' times out and needed to be aborted in an unsafe way. This may have corrupted the target process.
But the error does not catch for either the catch(DirectoryServicesCOMException) or the general, catch(Exception ex)
Instead, the code continues in the block and returns true.
Any reason why the try-catch does not catch the timed out error?
This is what I have discovered from here:
Binding against the AD has a serious overhead, the AD schema cache has to be loaded at the client (ADSI cache in the ADSI provider used by DirectoryServices). This is both network, and AD server, resource consuming - and is too expensive for a simple operation like authenticating a user account.
While it does not explain the behaviour of why the try-catch does not catch the error, it did point me to a workable solution using PrincipalContext instead.
This works without any delay or error:
private bool AuthenticateUser(string userName, string password)
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "EnterYourDomain"))
{
return context.ValidateCredentials(userName, password);
}
}