Click here to Skip to main content
15,882,017 members
Articles / Programming Languages / C#
Tip/Trick

Application Login through Active Directory (LDAP)

Rate me:
Please Sign up or sign in to vote.
4.85/5 (9 votes)
21 May 2013CPOL2 min read 128K   11.6K   44   5
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)


Written By
Software Developer (Senior)
Malaysia Malaysia
I've been working with various Microsoft Technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an attitude for learning new skills and utilizing that in my work.


--Amit Kumar
You can reach me at:
Facebook | Linkedin | Twitter | Google+

Comments and Discussions

 
GeneralMy vote of 5 Pin
VhatAmI1-Sep-17 6:04
VhatAmI1-Sep-17 6:04 
GeneralRe: My vote of 5 Pin
_Amy20-Dec-17 14:51
professional_Amy20-Dec-17 14:51 
QuestionHow to get password for network credentials? Pin
Devharsh Trivedi6-Jan-16 18:41
Devharsh Trivedi6-Jan-16 18:41 
QuestionHow can i resolve pricipal server connection down? Pin
Member 1070260824-Jun-15 21:06
Member 1070260824-Jun-15 21:06 
QuestionNice Pin
Member 1145021313-Feb-15 3:36
Member 1145021313-Feb-15 3:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.