The Lightweight Directory Access Protocol (LDAP) is an application protocol for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network

Directory services may provide any organized set of records, often with a hierarchical structure, such as a corporate electronic mail directory, Domains etc. LDAP is a client-server protocol for accessing a directory service.

In this example, we have authenticate the Domain user in an Organization.


First we need to add a reference of namespace “System.DirectoryServices” and see the below code,

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.DirectoryServices;

namespace ConsoleApplication3
{

public class LDAPAuthentication
{
//Private Member variables used to hold Intermediate Data
private string _path;
private string _filterAttribute = "OU";
//Constant Declaration
//Public Const e_Mail As String = "email"
//Public Const Display_Name As String = "displayName"
//Public Const Country_Name As String = "c"
//Public Const Organizational_Name As String = "o"
//Public Const Primary_Home_Phone As String = "homePhone"
//Public Const Primary_Phone_No As String = "telephoneNumber"
//Public Const Street_Address As String = "street"
//Public Const User_Created_Date As String = "whenCreated"
//Constructor, accepts the Path of Active Directory as argument
public LDAPAuthentication(string path)
{
    _path = path;
}

//Function Returns if the User is Valid or Not, provided the Login Name and Password
public bool IsAuthenticated(string domain, string username, string pwd)
{
    string domainAndUserName = domain + "\\" + username;
    DirectoryEntry entry = new DirectoryEntry(_path, domainAndUserName, pwd);
    try
    {
        object obj = new object();
        obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = default(SearchResult);
        result = search.FindOne();
        if (result == null)
        {
            return false;
        }
        _path = result.Path;
        _filterAttribute = result.Properties["cn"][0].ToString();
    }
    catch (Exception ex)
    {
        return false;
        throw new Exception("Error Authentication User " + ex.Message);
    }
    return true;
}
//Method to validate a User in the Domain
public bool IsUserAvailable(string domain, string userToFind, string userLogin, string userPass)
{
    string domainAndUserName = domain + "\\" + userToFind;
    DirectoryEntry entry = new DirectoryEntry(_path, userLogin, userPass);
    try
    {
        object obj = new object();
        obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + userToFind + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = default(SearchResult);
        result = search.FindOne();
        if (result == null)
        {
            return false;
        }
        _path = result.Path;
        _filterAttribute = result.Properties["cn"][0].ToString();
    }
    catch (Exception ex)
    {
        throw new Exception("Error Finding User " + ex.Message);
    }
    return true;
}

//Method Used to retrieve various Properties for an Authenticated User
public string GetActiveProperty(string propName)
{
    DirectorySearcher search = new DirectorySearcher(_path);
    search.Filter = "(cn=" + _filterAttribute + ")";
    search.PropertiesToLoad.Add(propName);
    System.Text.StringBuilder groupNames = new System.Text.StringBuilder();
    try
    {
        SearchResult result = default(SearchResult);
        result = search.FindOne();
        int propertyCount = result.Properties[propName].Count;
        string dn = null;
        string equalsIndex = null;
        string commaIndex = null;
        int propertyCounter = 0;

        for (propertyCounter = 0; propertyCounter <= propertyCount - 1; propertyCounter++)
        {
            dn = result.Properties[propName][propertyCounter].ToString();

            equalsIndex = dn.IndexOf("=", 1).ToString();
            commaIndex = dn.IndexOf(",", 1).ToString();
            if (equalsIndex == (-1).ToString())
            {
                return null;
            }
            groupNames.Append(dn.Substring((Convert.ToInt32(equalsIndex) + 1), (Convert.ToInt32(commaIndex) - Convert.ToInt32(equalsIndex)) - 1).ToString());
            groupNames.Append("|");
        }
    }
    catch (Exception ex)
    {

        throw new Exception("Error obtaining group names. " + ex.Message);
    }
    return groupNames.ToString();
}

}


class Program
{
static void Main(string[] args)
{
    LDAPAuthentication obj = default(LDAPAuthentication);
    obj = new LDAPAuthentication("LDAP://INDIAHOV.com");
    string i = null;
    //i = obj.GetActiveProperty("nsuresh")

    if (obj.IsUserAvailable("INDIALASON", "nsuresh", "nsuresh", "1234"))
    {
        Console.WriteLine("Ok");
    }

    if ((obj.IsAuthenticated("rkbabu", "rkbabu", "1234)$")))
    {
        Console.WriteLine("Ok");
    }
    else
    {
        Console.WriteLine("Not Ok");
    }

    Console.Read();

}
}
}


Here , I have passed the Domain and password to search the Active Directory and getting the result as Boolean.

Comments (0)