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.
- [HttpGet]
- [Route("authenticateuser/{username}/{password}")]
- public bool ADUserExists(string userName, string password) {
- string domainName = System.Environment.UserDomainName;
- string domainUserName = System.Environment.UserName;
- PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, domainUserName, ContextOptions.SimpleBind.ToString());
- bool isValid = pc.ValidateCredentials(userName.ToUpper(), password);
- if (isValid) {
- return true;
- } else {
- return false;
- }
- }
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:
localhost:52740/api/mapapicall/authenticateuser/testusername/testpassword