How to authenticate user against active directory

While developing an intranet application, I had to use Active Directory to authenticate the users. I thought I might need to use WMI. But I found a simple solution using PrincipalContext class from the System.DirectoryServices.AccountManagement namespace. You can use the ValidateCredentials() method. You need to pass the domain name as one of the parameter to this function. Here is the snippet.

using System.DirectoryServices.AccountManagement;
using System.Net.NetworkInformation;

string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;
using (var principalContext = new PrincipalContext(ContextType.Domain, domain))
    return principalContext.ValidateCredentials(username, password);

The PrincipalContext class only available from .Net Framework 3.5 onwards.

Happy Programming