Authenticating with Active Directory
Hi!
If you work in a corporate environment, chances are that your Windows machine is connected to a domain based on Active Directory. In today’s article, we’re going to write a very simple program that allows us to verify a user’s credentials for the domain using Active Directory.
In order to try this out, you’re going to need an Active Directory domain. In my case, I installed Windows Server 2008 R2 and followed these instructions to set up a domain, which I called “ranch.local”. You may also be able to connect to your domain at work to save yourself the trouble of setting this up.
Let us now create a new Console Application using either SharpDevelop or Visual Studio. After adding a reference to System.DirectoryServices.AccountManagement, add the following statement near the top of your Program.cs file:
using System.DirectoryServices.AccountManagement;
Next, remove any code in Main() and add a simple prompt for the username and password to authenticate against Active Directory:
// prompt for username
Console.Write("Username: ");
string username = Console.ReadLine();
// prompt for password
Console.Write("Password: ");
string password = Console.ReadLine();
For the authentication part, we can use a simple method described here. After obtaining a reference to the domain using the PrincipalContext class (specifying the domain as a parameter), we simply use the ValidateCredentials() method to perform the authentication. This gives us a boolean value indicating whether the authentication was successful or not.
// authenticate
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "RANCH"))
{
bool authenticated = pc.ValidateCredentials(username, password);
if (authenticated)
Console.WriteLine("Authenticated");
else
Console.WriteLine("Get lost.");
}
At this point, we need only add a simple statement to wait for user input before letting the application terminate:
Console.ReadLine();
Now, we can build our application and test it on the server (or on any machine that is part of the domain). First, let’s try a valid login:
Very good! And now, a user that doesn’t even exist:
Excellent! As you can see, it only takes a couple of lines of code to perform authentication against Active Directory. I hope you found this useful.
Reference: | Authenticating with Active Directory from our NCG partner Daniel DAgostino at the Gigi Labs blog. |