I need to validate the credentials that are used to connect to an AD server. If if pass invalid credentials to PrincipalContext(ContextType, String, String, String)
, PrincipalContext.ConnectedServer
throws a System.DirectoryServices.DirectoryServicesCOMException
which is discovered on the first use of the PrincipalContext
.
I am trying to test the credentials with PrincipalContext.ValidateCredentials(null, null)
but I am having issues. According to the .NET Core 2.0 docs
The ValidateCredentials method binds to the server specified in the constructor. If the username and password parameters are null, the credentials specified in the constructor are validated.
I create a connnection to the server.
string username = "username"
string password = "password"
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "my_domain.local", username, password);
And then to test the connection I try:
if (ctx.ValidateCredentials(null, null))
{
// This block does not get hit!
// This is surprising because the credentials are valid
}
Which has different behaviour to:
if (ctx.ValidateCredentials(username, password))
{
// Credentials are valid, this block gets hit
}
The docs lead me to believe these calls should behave identically yet I am experiencing different results. Why is this and what is the proper way to test a connection?