How to authenticate user against active directory

September 04, 2013 by Anuraj

.Net .Net 3.0 / 3.5 .Net 4.0 Windows Forms

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

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub