Dailycode.info

Short solution for short problems

Find user in active directory and get the properties

When you are developing an application that uses active directory users, without using the default membership provider, you'll need to write some default login logic. In my application a perform a login check and when users are added to the application, I perform a check if the users exists.

First the login check:

/// <summary>

/// Checks if the user exists in active directory and if the password is correct

/// </summary>

/// <param name="domain">Domain of the user</param>

/// <param name="username">Login name</param>

/// <param name="pwd">Password</param>

/// <returns>True=user is authenticated</returns>

public static bool IsAuthenticated(string domain, string username, string pwd)

{

    string domainAndUsername = domain + @"\" + username;

    string path = "";

 

    DirectoryEntry entry = new DirectoryEntry(path, domainAndUsername, pwd);

 

    try

    {

        DirectorySearcher search = new DirectorySearcher(entry);

 

        search.Filter = "(SAMAccountName=" + username + ")";

        search.PropertiesToLoad.Add("cn");

        SearchResult result = search.FindOne();

 

        if (null == result)

        {

            return false;

        }

    }

    catch (Exception ex)

    {

        throw ex;

    }

 

    return true;

}

This function simply checks if a user with password and login name exists in AD. We use username and password to create the directory entry and perform an action with this entry. If the username or the password is invalid, we get this error: Logon failure: unknown user name or bad password. 

The next AD action is to lookup if the user exists: 

/// <summary>

/// Checks if a user exists in active directory

/// </summary>

/// <param name="userName">Users name</param>

/// <returns>True=user exists</returns>

public static bool FindUserInAD(string userName)

{

    //string domainAndUsername = domain + @"\" + username;

    string path = "";

    //DirectoryEntry entry = new DirectoryEntry(path, @"pmi\g-labautomation", "Ordina$78");

    DirectoryEntry entry = new DirectoryEntry(path);

    try

    {

        DirectorySearcher search = new DirectorySearcher(entry);

 

        search.Filter = "(SAMAccountName=" + userName + ")";

        search.PropertiesToLoad.Add("cn");

        SearchResult result = search.FindOne();

 

        if (null == result)

        {

            return false;

        }

    }

    catch (Exception ex)

    {

        throw ex;

    }

 

    return true;

}

 

Here's an example of active directory properties with dummy values!

Last a simple function to get the basic properties for a user from AD:

/// <summary>

/// Returns Ilist with account info

/// </summary>

/// <param name="userName">Users name</param>

/// <returns>List

/// index 1: displayname

/// index 2: accountname

/// index 3: email</returns>

public static List <string> GetUserFromAD(string userName)

{

    //string domainAndUsername = domain + @"\" + username;

    string path = "";

    //DirectoryEntry entry = new DirectoryEntry(path, @"pmi\g-labautomation", "Ordina$78");

    DirectoryEntry entry = new DirectoryEntry(path);

    List<string> returnList = new List<string>();

    entry.AuthenticationType = AuthenticationTypes.FastBind;

 

    try

    {

        DirectorySearcher search = new DirectorySearcher(entry);

 

        search.Filter = "(SAMAccountName=" + userName + ")";

        //search.PropertiesToLoad.Add("cn");

        search.PropertiesToLoad.Add("mail");

        search.PropertiesToLoad.Add("displayName");

        search.PropertiesToLoad.Add("SAMAccountName");

       

        SearchResult result = search.FindOne();

 

        if (null == result)

        {

            return null;

        }

        else

        {

            returnList.Add(result.Properties["displayName"][0].ToString());

            returnList.Add(result.Properties["SAMAccountName"][0].ToString());

            try

            {

                returnList.Add(result.Properties["mail"][0].ToString());

            }

            catch

            {

                returnList.Add("no_email");

            }

            return returnList;

        }

    }

    catch (Exception ex)

    {

        throw ex;

    }

 

}