<< Back To All Blogs
Validate a Windows Username and Password against Active Directory
Friday, January 8th, 2010
I came across a need to validate a windows username and password explicitly against a domain server for the purpose of verification. I have had to implement just about every other scenario with regards to authentication in the past already, but normally because the user is already authenticated, .NET will handle Domain negotiation on it's own so you don't have to get into this, until you reach the scenario that you want to verify the user's credentials in whatever type of application.
This turned out to be much easier then I expected, as handling NTLM domain authentication in HTTP requests can be quite the task at times, but to my surprise (and delight), you simply need the following:
PrincipalContext myContext = new PrincipalContext(ContextType.Domain, "MyDomain");
bool validUser = myContext.ValidateCredentials("MyDomainMyUsername", "MyPassword");
validUser will return true if you are successfully authenticated.
A few other notes:
1. These are used from the System.DirectoryServices.AccountManagement namespace
2. The assembly for this namespace is not included by default in most scenarios, so you'll need to add a reference to the System.DirectoryServices.AccountManagement.dll assembly
3. Even though you are specifying the domain in your PricipalContext, it is important to note that this won't work unless you include your full domain and username path for the username argument in ValidateCredentials. For example, nerdyhearn would not work for the username validation, whereas nerdydomainnerdyhearn would.
Authenticatin' Tom Out.
Comparing XML files in C# Using Microsoft's Diff and Patch Tool
Creating High Quality Images with C# and GDI
Retrieving Text from Win32 SDK's GetLastError() in C#
Creating a reusable web client for PUT, POST, and DELETE in C#
Determining if a computer is a laptop or desktop in C#
Currently no comments.
Add A Comment
Email Address: (not public, used to send notifications on further comments)
Enter the text above, except for the 1st and last character: