【发布时间】: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#