【问题标题】:Why is PrincipalContext ValidateCredentials throwing an exception when given incorrect credentials?为什么 PrincipalContext ValidateCredentials 在给定不正确的凭据时会引发异常?
【发布时间】:2017-12-07 17:50:28
【问题描述】:

我正在尝试对用户进行身份验证。通过 PrincipalContext 进行的身份验证可以在正确的用户名和密码下正常工作,但是在使用不正确的凭据进行测试时,ValidateCredentials 会抛出 System.Exception 而不是返回 false。异常只是说明“用户名或密码不正确”。堆栈跟踪如下:

   at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADs.Get(String bstrName)
   at System.DirectoryServices.AccountManagement.CredentialValidator.BindSam(String target, String userName, String password)
   at System.DirectoryServices.AccountManagement.PrincipalContext.ValidateCredentials(String userName, String password)
   at hcv.Core.AuthenticationSystem.Services.WindowsAuthenticationService.<>c__DisplayClass3_0.<AuthenticateAsync>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)" string

而且代码非常简单:

using (var pc = new PrincipalContext(_contextType, _domain))
{
    var isAuthenticated = pc.ValidateCredentials(username, password);
    return isAuthenticated;
}

我目前正在通过捕获错误、检查消息并在用户名或密码消息不正确时返回 false 以及如果不是则重新抛出来解决此问题,但这感觉很糟糕。

有谁知道为什么抛出异常而不是简单地为无效凭据返回 false?

【问题讨论】:

    标签: c#


    【解决方案1】:

    ContextOptions添加到方法ValidateCredentials

    有多种选择取决于ContextType

    在这里查看:https://msdn.microsoft.com/en-us/library/bb300969(v=vs.110).aspx

    【讨论】:

    • 我查看了文档并尝试了各种ContextOptions 设置,但均无济于事。对于我认为可以尝试的每种设置,ValidateCredentials 调用仍然会引发异常,而不是像文档中所描述的那样简单地返回 false。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    相关资源
    最近更新 更多