Monday, March 7, 2011

Verifying a Username/Password using Active Directory

Really simple to do in .NET / C#. Its one of the places where the going the full MS Stack helps.

Here is a simple function that will do the bulk of the work for you.

A using directiive :

using System.DirectoryServices;

An assembly reference (System.DirectoryServices ... obviously):

And this function:

/// Authenticates user name and password on the specified domain
/// Domain Name
/// User Name
/// User Password
/// True if user name and password are valid on domain
public bool AuthenticateUser(string domainName, string userName, string password)
  bool ret = false;
    DirectoryEntry de = new DirectoryEntry("LDAP://" + domainName, userName, password);
    DirectorySearcher dsearch = new DirectorySearcher(de);
    SearchResult results = null;

    results = dsearch.FindOne();

    ret = true;
    ret = false;

  return ret;

A sample call:


Also you can get the current domain the user is logged into using a static property on Environment: