How To Validate Username And Password Using Active Directory

I am making a Web API endpoint call and passing username and password, and validating the given username and password from Windows active directory and returning the status.

What is Active Directory?

Active Directory saves data as objects. An object is a single element, such as a user, group, application or device, such as a printer. Objects are normally defined as either resources like printers or computers or security principals like users or groups.
  1. [HttpGet]  
  2. [Route("authenticateuser/{username}/{password}")]  
  3. public bool ADUserExists(string userName, string password) {  
  4.     string domainName = System.Environment.UserDomainName;  
  5.     string domainUserName = System.Environment.UserName;  
  6.     PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, domainUserName, ContextOptions.SimpleBind.ToString());  
  7.     bool isValid = pc.ValidateCredentials(userName.ToUpper(), password);  
  8.     if (isValid) {  
  9.         return true;  
  10.     } else {  
  11.         return false;  
  12.     }  
  13. }  
In the given code snippet, we have an API endpoind with two parameters --  username, password. After hitting the function, you need to have Windows domain name and domain username, then make an object for PrincipalContext and pass domain name and username. Next you need to validate credentials based on given username and password and return the result in true or false. If validated, then return true otherwise return false.
Let’s test the given scenario; open browser and give endpoint url with username and password:
How To Validate Username And Password Using Active Directory