If you’re working in an academic or large corporate or government setting, changes are you’re going to have a network in place using Active Directory or an open-source equivalent. Every user in the organization will have some sort of an account to use. If you’re building an internal web-application or desktop-application, it doesn’t make a lot of sense to give the user another set of credentials. Instead, you can validate users by checking the permissions existing Active Directory accounts.
The source code to check a user’s credentials in Active Directory using C# or Visual Basic is actually fairly minimal. This works with both ASP.NET and with Windows FormsĀ (or WPF for that matter) if you’re building a desktop application.
Here’s how to do it:
(1) Reference the appropriate library
You’ll need to make use of the System.DirectoryServices library that comes with Visual Studio. You can add this to your ASP.NET code-behind page or your C# class for your Windows forms like this.
using System.DirectoryServices;
(2) Create An Authentication Function.
Here’s a basic function that will check a user’s permissions on a given domain. Essentially, it will try to create an Active Directory entry using the provided credentials, and it can successfully create a valid entry, we know that the user is authenticated. Otherwise, it’ll return false.
public bool AuthenticateActiveDirectory(string Domain, string UserName, string Password)
{
try
{
DirectoryEntry entry = new DirectoryEntry(“LDAP://” + Domain, UserName, Password);
object nativeObject = entry.NativeObject;
return true;
}
catch (DirectoryServicesCOMException) { return false; }
}
That’s really all there is to it. Microsoft has an extensive aritcle on MSDN that covers active directory authentication in .NET that you might want to check out as well.