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


Charles BurnsPosted Jan 4, 2023, 10:48 PM
Please don't post security-related code if you do not understand security. This code has exposed user passwords to potentially over 40,000 applications. First, everyone's username and password are readable by anyone that can look at server logs or see redirect URLs because HTTP GET params are logged by default on most systems. Second, your code sends this information unprotected because you use disable encryption using only SimpleBind, which the official documentation warns agains. Besides sending everyone's password in plain text, this also authenticates users with expired passwords (almost no one knows this; see Wiktor Zychla's post from June 18, 2021). Finally, your code uppercases the login name, which will immediately invalidate the login on any LDAP server configured to be case sensitive, unless the company's naming convention happens to always be ALL UPPERCASE. Unlikely. There is nothing wrong with not understanding security -- most developers do not, including myself, but there IS something wrong with posting code that will lead to user logins and passwords being handled insecurely.