Click here to Skip to main content
15,878,430 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am getting exception "Incorrect username or password exception" while doing AD Authentication in c#. I am using with c# and framework is 4.6.1. I have set the Windows authentication mode Enabled and Anonymous Disabled. I am getting exception on reaching the code
SearchResult sr = ds.FindOne();
.Till that no exception is there. I am getting domain, domain user all correctly.

What I have tried:

My code is as below:
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 solution

There is not any error message is mentioned in the question. Note, if the credentials are incorrect, the ds.FindOne() method will throw an exception, as it relies on the user's credentials for connecting to AD. This method may not be the most efficient means of validating credentials. For improved performance. If you work on .NET 3.5 or newer (yes you are using 4.6.1), you can use the System.DirectoryServices.AccountManagement namespace and easily verify your credentials:
// 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");
Reference: Read all about it here:[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900