It’s a shame how many applications, even popular ones, have huge security gaps regarding passwords. The most recent case to hit the news was Reddit but this is only the tip of the iceberg. How many internals applications out there uses plain text password. A whole lot! You probably did it at some point, and so do I. But the object of this post is not to rant and whine about that situation. I just want to show those who don’t know about it how easy it is to integrate Windows Active Directory authentication to your application. So now, if you read this my blog, no more excuses to have that “password” field in your database.
First you need to add a reference in your project to System.DirectoryServices
Here is the code, I will catch you up on the other side.
String Username = "username";
String domainAndUsername = "domain\\username";
String Password = "password";
DirectoryEntry entry = new DirectoryEntry("", domainAndUsername, Password);
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + Username + ")";
// search.FindOne() will throw an exception if there is a bad username/password combination provided
SearchResult result = search.FindOne();
throw new System.Security.SecurityException("Access denied.");
Pretty straightforward isn’t it? Obviously, you need to change the first lines with the user’s input but other than that, it’s all that’s needed for a basic username/password authentication using Active Directory. You can copy this code and use it in your application and see for yourself. If you want more information on what you can get from Active Directory, there is a good article on the different name attributes here. You can also go to the homepage of System.DirectoryService on MSDN here.
I want to add that I’m not an Active Directory expert. If a reader see something wrong with this code, please let me know and I’ll update it right away!
How to create user accounts in active directory using C#