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;
  try
  {
    DirectoryEntry de = new DirectoryEntry("LDAP://" + domainName, userName, password);
    DirectorySearcher dsearch = new DirectorySearcher(de);
    SearchResult results = null;

    results = dsearch.FindOne();

    ret = true;
  }
  catch
  {
    ret = false;
  }

  return ret;
}


A sample call:

AuthenticationUser("eapac","basarat","basarat");


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

Environment.UserDomainName.ToLower();



Enjoy!

Source: http://weblogs.asp.net/psheriff/archive/2011/02/28/wpf-login-verification-using-active-directory.aspx