In this tutorial, we will discuss two methods to validate user credentials (Username and Password) in Active Directory using C# code.
First Method Using System.DirectoryServices:
Step 1 – Add a reference to System.DirectoryServices dll into your project.
Step 2 – Add the below namespace to your code file
using System.DirectoryServices;
Step 3 – Use the below code for credentials validation
private bool IsValidUser() { bool isValid = false; try { DirectoryEntry entry = new DirectoryEntry("LDAP://yourdomain.com", "username", "password"); object nativeObj = entry.NativeObject; isValid = true; } catch (DirectoryServicesCOMException comex) { //Not Authenticated. comex.Message will return the reason } catch (Exception ex) { //optional } return isValid; }
Second Method Using System.DirectoryServices.AccountManagement:
For .Net Frameworks 3.5 or newer we can use System.DirectoryServices.AccountManagement to verify credentials.
Step 1 – Add a reference to System.DirectoryServices.AccountManagement dll into your project.
Step 2 – Add the below namespace to your code file
using System.DirectoryServices.AccountManagement;
Step 3 – Use the below code for credentials validation
try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "yourdomain.com")) //No need to add LDAP:// with the domain { // validate the credentials bool isValid = pc.ValidateCredentials("username", "password"); if(isValid) { //User credentials validated } else { //Not authenticated } } } catch(Exception ex) { }
Conclusion
We have covered two of the many methods in this blog post. Now you know how to validate user credetials against Active Directory
Don’t forget to check out this awesome course on Udemy Design Patterns in C# and .NET
Also, don’t forget to check our other tutorial similar to this topic, where we explained how to create user in active directory using C# code
**Thank You**