How to Authenticate a User in Active Directory using ASP.NET

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.

Comments

  1. This is awesome and will come in handy. I’m usually lazy and just use IIS to handle the AD authentication side.
    Now that you’ve been able to authenticate to AD, how hard would it be to create a function that allows a user to change their password?

  2. It’s actually not that difficult at all. You just create a DirectoryEntry object and use the .Invoke method to change the password.

    Here’s a link to some example code:

    http://www.primaryobjects.com/CMS/Article66.aspx

  3. Just what I needed. Thanks for the tutorial.

  4. That’s very good function and work very welll. Thanks to put a usful article. tanks again

  5. This doesn’t work correctly. If you do something like:

    DirectoryEntry entry = new DirectoryEntry(“LDAP://” + Domain, “someone”, String.Empty);
    object nativeObject = entry.NativeObject;

    It does not fail even though I’m sure the user “someone” with no password does not exist.

Speak Your Mind

*