Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Application Login through Active Directory (LDAP)

4.85/5 (9 votes)
21 May 2013CPOL2 min read 129.7K   11.6K  
Validating the client using Lightweight Directory Access Protocol (LDAP)

Introduction

Sometimes, we need to validate our client using the Active Directory. Here in this tip, I am validating the user using a protocol called Lightweight Directory Access Protocol (LDAP). Many times, I have given the same explanation to others and now I am making it as a tip so that others can get it easily from CodeProject.

Background

Let me go through the explanation of LDAP. LDAP is an application protocol for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network.

Now, while reading this again, a question comes to mind, "what is Active Directory?" It is a special-purpose database which is designed to handle a large number of read and search operations and a significantly smaller number of changes and updates. It also holds the information about the user in current domain or network.

In order to validate the user from Active Directory, we need to use LDAP.

Using the Code

Validating a User

In order to validate the user from AD (Active Directory), we need to have LdapConnection. Then using NetworkCredential class, we can easily validate the user. I have created a sample function here which will return the boolean result (if user credentials match active directory, then it'll return true otherwise it'll return false).

C#
public static bool fnValidateUser() 
{
    bool validation;
    try
    {
        LdapConnection lcon = new LdapConnection
        		(new LdapDirectoryIdentifier((string)null, false, false));
        NetworkCredential nc = new NetworkCredential(Environment.UserName, 
                               "MyPassword", Environment.UserDomainName);
        lcon.Credential = nc;
        lcon.AuthType = AuthType.Negotiate;
        // user has authenticated at this point,
        // as the credentials were used to login to the dc.
        lcon.Bind(nc);
        validation = true;
    }
    catch (LdapException)
    {
        validation = false;
    }
    return validation;
}

Listing All Users

If you want to list all the user's from current domain, then you can use DirectoryEntry class. Here is an example for that:

C#
public static void fnListAllUser()
{
    DirectoryEntry directoryEntry = new DirectoryEntry
    		("WinNT://" + Environment.UserDomainName);
    string userNames = "";
    string authenticationType="";
    foreach (DirectoryEntry child in directoryEntry.Children)
    {
        if (child.SchemaClassName == "User")
        {
            userNames += child.Name + 
            	Environment.NewLine; //Iterates and binds all user using a newline
            authenticationType += child.Username + Environment.NewLine;
        }
    }
    Console.WriteLine("************************Users************************");
    Console.WriteLine(userNames);
    Console.WriteLine("*****************Authentication Type*****************");
    Console.WriteLine(authenticationType);
}

If you want to get the user names with their respective groups, then you need to use PrincipalContext and GroupPrincipal class. See this example:

C#
public static void fnGetListOfUsers() {
    // set up domain context
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 
    // find the group in question
    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "USERS"); 
    // if found....
    if (group != null)
    {
        // iterate over members
        foreach (Principal p in group.GetMembers())
        {
            Console.WriteLine("{0}: {1}", 
            	p.StructuralObjectClass, p.DisplayName);
            // do whatever you need to do to those members
        }
    }
}

Listing the Details of a User

And also, if you want to get all the details of a particular user, then you need to use PropertyCollection class. See this example:

C#
public static void fnImp() {
    using (var context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName))
    {
        using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
        {
            foreach (var result in searcher.FindAll())
            {
                DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                if ((string)de.Properties["givenName"].Value == Environment.UserName)
                {
                    //Console.WriteLine("First Name: " + 
                    //de.Properties["givenName"].Value);
                    //Console.WriteLine("Last Name : " + 
                    //de.Properties["sn"].Value);
                    //Console.WriteLine("SAM account name   : " + 
                    //de.Properties["samAccountName"].Value);
                    //Console.WriteLine("User principal name: " + 
                    //de.Properties["userPrincipalName"].Value);
                    Console.WriteLine();
                    PropertyCollection pc = de.Properties;
                    foreach (PropertyValueCollection col in pc)
                    {
                        Console.WriteLine(col.PropertyName + " : " + col.Value);
                        Console.WriteLine();
                    }
                }
            }
        }
    }
} 

End Point

This tip is a part of my previous answers which I gave in CodeProject for the question Active Directory login[^].

Thank you for spending your precious time reading this tip/trick. Any suggestions will be appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)