Click here to Skip to main content
14,743,033 members
Articles » General Programming » Internet / Network » LDAP
Posted 12 Sep 2012


42 bookmarked

Application Login through Active Directory (LDAP)

Rate me:
Please Sign up or sign in to vote.
4.85/5 (9 votes)
21 May 2013CPOL
Validating the client using Lightweight Directory Access Protocol (LDAP)


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.


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).

public static bool fnValidateUser() 
    bool validation;
        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.
        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:

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("*****************Authentication Type*****************");

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

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:

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: " + 
                    //Console.WriteLine("Last Name : " + 
                    //Console.WriteLine("SAM account name   : " + 
                    //Console.WriteLine("User principal name: " + 
                    PropertyCollection pc = de.Properties;
                    foreach (PropertyValueCollection col in pc)
                        Console.WriteLine(col.PropertyName + " : " + col.Value);

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.


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


About the Author

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 7:04
MemberVhatAmI1-Sep-17 7:04 
GeneralRe: My vote of 5 Pin
_Amy20-Dec-17 15:51
professional_Amy20-Dec-17 15:51 
QuestionHow to get password for network credentials? Pin
Devharsh Trivedi6-Jan-16 19:41
MemberDevharsh Trivedi6-Jan-16 19:41 
QuestionHow can i resolve pricipal server connection down? Pin
Member 1070260824-Jun-15 22:06
MemberMember 1070260824-Jun-15 22:06 
QuestionNice Pin
Member 1145021313-Feb-15 4:36
MemberMember 1145021313-Feb-15 4: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.