logo

,

Validate Username and Password in Active Directory C#

In this article, we will discuss two approaches to validate user credentials in Active Directory using C#

  1. System.DirectoryServices
  2. System.DirectoryServices.AccountManagement

 

1. 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;
    }

2. 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)
            {

            }

One Response

Leave a Reply

Your email address will not be published.

Share on facebook
Share on twitter
Share on linkedin

Related articles