Click here to Skip to main content
15,891,372 members
Articles / Programming Languages / C#

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 128.2K   11.6K   44  
Validating the client using Lightweight Directory Access Protocol (LDAP)
#region NameSpaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices.Protocols;
using System.Net;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
#endregion

namespace ActiveDirectoryLogin
{
    class Program
    {
        #region Validating User
        /// <summary>
        /// Validation for a single user to the active directory
        /// </summary>
        /// <returns></returns>
        public static bool fnValidateUser()
        {
            bool validation;
            try
            {
                LdapConnection lcon = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
                NetworkCredential nc = new NetworkCredential(Environment.UserName, "kals123", Environment.UserDomainName);
                lcon.Credential = nc;
                lcon.AuthType = AuthType.Negotiate;
                lcon.Bind(nc); // user has authenticated at this point, as the credentials were used to login to the dc.
                validation = true;
            }
            catch (LdapException)
            {
                validation = false;
            }
            return validation;
        }
        #endregion

        #region Listing All Users
        /// <summary>
        /// Lists all the users from current domain
        /// </summary>
        public static void fnListAllUser()
        {
            try
            {
                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);
            }
            catch (Exception)
            {
                Console.WriteLine("Network error occured.");
            }
        }
        #endregion

        #region user names with groups
        /// <summary>
        /// Getting user names with respective groups
        /// </summary>
        public static void fnGetListOfUsers()
        {
            try
            {
                // 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
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Network error occured.");
            }
        }
        #endregion

        #region User Details from AD
        /// <summary>
        /// Getting a particular user details from user's active directory
        /// </summary>
        public static void fnImp()
        {
            try
            {
                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();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Network error occured.");
            }
        }
        #endregion

        #region Main
        static void Main(string[] args)
        {
            fnListAllUser();
            fnImp();
            fnGetListOfUsers();
            Console.WriteLine(fnValidateUser());
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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