Testing a `PrincipalContext` using `ValidateCreden

2019-08-07 08:39发布

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?

1条回答
对你真心纯属浪费
2楼-- · 2019-08-07 08:56

I was able to replicate this by running your code under a local account on my computer and passing valid domain credentials in the constructor. ValidateCredentials(null, null) does indeed fail.

This sounds like a bug, either in the code or in the documentation, so I've filed a bug on GitHub: https://github.com/dotnet/corefx/issues/29369

Edit: looks like they've decided to leave the implementation as-is and correct the documentation.

查看更多
登录 后发表回答