如何解决在C#中进行AD身份验证时用户名或密码错误的异常?


在 C# 中进行 AD 身份验证时,我收到异常“用户名或密码错误异常”。 我正在使用 asp.net 和 c#,框架是 4.6.1。 我已将 Windows 身份验证模式设置为启用并禁用匿名。 我在到达代码时遇到异常

SearchResult sr = ds.FindOne();

直到那一刻,无一例外。 我正确获取域、域用户。

我尝试过的:

我的代码如下:

Common.WriteDDSLog("ValidateWindowsUser()-Process Started for LoginId:" + txtLoginID.Text);
           //Added by Varun T V
           //Checks the user is active or not before sending credentials to Active Directory
           //Will send request to AD only when user is active
           BLL_Users objUser = new BLL_Users();
           string errorCode = "", errorMsg = "";
           DataSet dsUserExists = new DataSet();
           dsUserExists = objUser.CheckUserActiveOrExists(txtLoginID.Text.Trim(), ref errorCode, ref errorMsg);
           if (dsUserExists.Tables[0].Rows.Count > 0)
           {

               // Directory path
               string path = "LDAP://" + Domain;
               DirectoryEntry de = new DirectoryEntry(path);

               // Provide credentials to get to domain
               de.Username = Domain + "\\" + sUser;
               de.Password = sPassword;
               de.AuthenticationType = AuthenticationTypes.Secure;

               // Search result
               DirectorySearcher ds = new DirectorySearcher(de, null, new string[] { "distinguishedName" });
               SearchResult sr = ds.FindOne();

               if (sr != null)
               {
                   bSearchResult = true;

               }
           }

解决方案1

问题中没有提到任何错误消息。 请注意,如果凭据不正确,ds.FindOne() 方法将引发异常,因为它依赖于用户的凭据来连接到 AD。 此方法可能不是验证凭据的最有效方法。 为了提高性能。 如果您使用 .NET 3.5 或更高版本(是的,您正在使用 4.6.1),您可以使用 System.DirectoryServices.AccountManagement 命名空间并轻松验证您的凭据:

C#
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}

参考:在这里阅读所有内容:

[^]

コメント

タイトルとURLをコピーしました