Sunday, 13 July 2014

Validate the User Exist in the ActiveDirectory along with credentials and get the user info using LDAP Connection

In this article we are going to see how to find out whether a user is valid user along with password and get the user information using LDAP Connection, for this First we have to check before whether user in LDAP server.

Many of the configuration details should be needed and need to be understand before given as input.

Name *        :      LDAP
Host *          :     server.example.com {or} 123.12.44.22
Port *           :    389 { for SSL 636}
Account        :    cn=Manager,dc=example,dc=com
Password     :    secret
Base DN *   :    dc=example,dc=com
Login *         :    uid
LoginPass *  :    UserPassword

From the above input the mandatory fields are metion in * symbol Account is corresponds to the LDAP Account and Password is used to access the LDAP server, First we have to connect the LDAP server using that credentials, then iterate the users present in the server or select the particular user and get there LDAP user distinguished name to get the information of user as attributes.

Some of the LDAP Attributes and there Examples with explanation

Example
CN - Common Name
CN=Jhon Filder.  Actually, this LDAP attribute can be made up from givenName joined to SN.
CN
 'Name' in the LDAP provider.
CN is a mandatory property. 
description
displayName
displayName = Jhon Filder
mail
Get the mail id of the user
DN - also distinguishedName
DN is simply the most important LDAP attribute.
CN=Jay Jamieson, OU= Newport,DC=cp,DC=com
givenName
Firstname also called Christian name
homeDrive
Home Folder : connect.  Tricky to configure
name
name = Jhon Filder.  Exactly the same as CN.
objectCategory
Defines the Active Directory Schema category. For example, objectCategory = Person
objectClass
objectClass = User.  Also used for Computer, organizationalUnit, even container.  Important top level container.
physicalDeliveryOfficeName
Office! on the user's General property sheet
profilePath
Roaming profile path: connect.  Trick to set up
sAMAccountName
This is a mandatory property, sAMAccountName = name.  The old NT 4.0 logon name, must be unique in the domain. 
sAMAccountName
If you are using an LDAP provider 'Name' automatically maps to sAMAcountName and CN. The default value is same as CN, but can be given a different value.
SN
SN = Filder. This would be referred to as last name or surname.
userAccountControl
Used to disable an account.  A value of 514 disables the account, while 512 makes the account ready for logon.
userPrincipalName
userPrincipalName = name@sm.com  Often abbreviated to UPN, and looks like an email address.  Very useful for logging on especially in a large Forest.  Note UPN must be unique in the forest.
Examples of Exchange Specific LDAP attributes
homeMDB 
Here is where you set the Mail Store
legacyExchangeDN
Legacy distinguished name for creating Contacts. In the following example,
Jhon Filder is a Contact in the first administrative group of GUYDOMAIN: /o=GUYDOMAIN/ou=first administrative group/cn=Recipients/cn=Jhon Filder
mail
An easy, but important attribute.  A simple SMTP address is all that is required gilli@ourdom.com
mAPIRecipient - FALSE
Indicates that a contact is not a domain user.
mailNickname
Normally this is the same value as the sAMAccountName, but could be different if you wished.  Needed for mail enabled contacts.
mDBUseDefaults
Another straightforward field, just the value to:True
msExchHomeServerName
Exchange needs to know which server to deliver the mail.  Example:
/o=YourOrg/ou=First Administrative Group/cn=Configuration/cn=Servers/cn=MailSrv
proxyAddresses
As the name 'proxy' suggests, it is possible for one recipient to have more than one email address.  Note the plural spelling of proxyAddresses.
 targetAddress
SMTP:@ e-mail address.  Note that SMTP is case sensitive.  All capitals means the default address.
 showInAddressBook
Displays the contact in the Global Address List.
c
Country or Region
company
Company or organization name
department
Useful category to fill in and use for filtering
homephone
Home Phone number, (Lots more phone LDAPs)
l  (Lower case L)
L = Location.  City ( Maybe Office
location
Important, particularly for printers and computers.
manager
Boss, manager
mobile
Mobile Phone number
ObjectClass
Usually, User, or Computer
OU
Organizational unit.  See also DN
pwdLastSet
Force users to change their passwords at next logon
postalCode
Zip or post code
st
State, Province or County
streetAddress
First line of address
telephoneNumber
Office Phone
userAccountControl
Enable (512) / disable account (514)




Use can see a list of attributes and there usages along with sample values let we start the coding.

namespace LdapAuth
{
    public class User
    {
        public string DISTINGUISHEDNAME { set; get; }
        public string UID { getset; }
        public string NAME { getset; }
        public string DISPLAYNAME { getset; }
        public string FIRSTNAME { getset; }
        public string LASTNAME { getset; }
        public string MAIL { getset; }
        public string OU { getset; }    
    }


    public class LdapRequest
    {
        public LdapRequest(string hostName, string baseDn, string ldapAccUser, string ldapAccPassword)
        {
            this.HostName = hostName;
            this.BaseDn = baseDn;
            this.LdapAccUser = ldapAccUser;
            this.LdapAccPassword = ldapAccPassword;
        }

        public string HostName { private set; get; }
        public string BaseDn { set; get; }
        public string LdapAccUser { private set; get; }
        public string LdapAccPassword { private set; get; }

        [SecurityPermission(SecurityAction.Demand)]
        public User Authenticate(string userName, string password)
        {
            using (var ldap = new LdapConnection(new LdapDirectoryIdentifier(this.HostName)))
            {
                ldap.SessionOptions.ProtocolVersion = 3;

                if (!string.IsNullOrEmpty(LdapAccPassword))
                    ldap.Credential = new NetworkCredential(LdapAccUser, LdapAccPassword);
                
                ldap.AuthType = AuthType.Basic;
                ldap.Bind();

                /* Get the distinguish name of particular user */
                var distinguishname = GetDn(ldap, userName);

                if (distinguishname != null)
                {
                    try
                    {
                        ldap.AuthType = AuthType.Basic;
                        ldap.Bind(new NetworkCredential(distinguishname, password));
                        /* Get the user attributes  */
                        return GetUser(ldap, distinguishname);
                    }
                    catch (DirectoryOperationException ex1)
                    {
                        Console.WriteLine(ex1.Message);
                    }
                    catch (LdapException ex2)
                    {
                        Console.WriteLine(ex2.Message);
                    }
                }
            }
            return null;
        }

        private String GetDn(LdapConnection ldap, String userName)
        {

            var request = new SearchRequest(this.BaseDn, string.Format("uid={0}", userName),                                             SearchScope.Subtree);
            var response = (SearchResponse)ldap.SendRequest(request);

            if (response.Entries.Count > 0)
            {
                return response.Entries[0].DistinguishedName;
            }

            return null;

        }

        private User GetUser(LdapConnection ldap, String dn)
        {
            var request = new SearchRequest(dn, "(objectclass=*)", SearchScope.Base);
            var response = (SearchResponse)ldap.SendRequest(request);
            if (response.Entries.Count > 0)
            {
                return Instance(response.Entries[0]);
            }
            return null;
        }

        private User Instance(SearchResultEntry entry)
        {
            User obj = new User();
       
            foreach (DictionaryEntry attr in entry.Attributes)
            {
                var name = attr.Key.ToString().ToUpperInvariant();
                var values = (DirectoryAttribute)attr.Value;

                switch (name)
                {
                    case "DISTINGUISHEDNAME":
                        obj.DISTINGUISHEDNAME = values[0].ToString(); 
                        break;
                    case "UID"
                        obj.UID = values[0].ToString(); 
                        break;
                    case "CN":
                        obj.NAME = values[0].ToString(); 
                        break;
                    case "DISPLAYNAME"
                        obj.DISPLAYNAME = values[0].ToString(); 
                        break;
                    case "GIVENNAME"
                        obj.FIRSTNAME = values[0].ToString(); 
                        break;
                    case "SN":
                        obj.LASTNAME = values[0].ToString(); 
                        break;
                    case "MAIL":
                        obj.MAIL = values[0].ToString(); 
                        break;
                    case "OU":
                        obj.OU = values[0].ToString();
                        break;
                }
            }
            return obj;
        }

    }
}


Next call the code form the Application


class App
    {
        static void Main(string[] args)
        {

            var server = "113.14.82.23";
            var baseDn = "dc=macrosys,dc=com";
            var domainusername = "cn=root,dc=macrosys,dc=com";
            var domainpassword = "domainpass12*";
            var userName = "chrisbaker";
            var password = "chris#23!";

            var ldap = new LdapRequest(server, baseDn, domainusername, domainpassword);
            var user = ldap.Authenticate(userName, password);

            if (user != null)
            {
                Console.WriteLine("User ID   : " + user.UID);
                Console.WriteLine("Name      : " + user.NAME);
                Console.WriteLine("First name: " + user.FIRSTNAME);
                Console.WriteLine("Last name : " + user.LASTNAME);
                Console.WriteLine("Email ID  : " + user.MAIL);
                Console.WriteLine("Distinguish Name : " + user.DISTINGUISHEDNAME);
            }
            else
            {
                Console.WriteLine("Authorization failed.");
            }

            Console.ReadKey();
        }

    }



From the above code you can able to validate user existence in LDAP server along with credentials.





No comments:

Post a Comment