1

I am new to LDAP and C# coding, wanted to validate the given user password in LDAP server using c#. I am using ApacheDS 2.0.0 for Open LDAP server and I have following code to access the server. I am trying to use the method to validate the password of the user from the Ldap server end. Could anyone suggest what method can I use for the validation.

 using System;
 using System.Net;
 using System.Security.Permissions;
 using System.DirectoryServices;
 using System.DirectoryServices.Protocols;
 using System.DirectoryServices.AccountManagement;

namespace LdapConnection
{
[DirectoryServicesPermission(SecurityAction.LinkDemand, Unrestricted = true)]
public class LdapConnect
{      

    public static void Main(string[] args)
    { 
        try
        {
            // Create the new LDAP connection
            LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier("localhost", 
            10389); // _msdcs.cc.ebs.corp:389
            System.DirectoryServices.Protocols.LdapConnection ldapConnection =
            new System.DirectoryServices.Protocols.LdapConnection(ldi);
            Console.WriteLine("LdapConnection is created successfully.");
            ldapConnection.AuthType = AuthType.Basic;
            ldapConnection.SessionOptions.ProtocolVersion = 3;
            NetworkCredential nc = new NetworkCredential("uid=admin,ou=system", 
            "password"); //password
            ldapConnection.Bind(nc);
            Console.WriteLine("LdapConnection authentication success");
            
            var request = new SearchRequest("o=Company", " 
            (objectClass=inetOrgPerson)", 
            System.DirectoryServices.Protocols.SearchScope.Subtree, null);
            var response = (SearchResponse)ldapConnection.SendRequest(request);
            foreach (SearchResultEntry entry in response.Entries)
            {
                if (entry is null)
                {
                    continue;
                }
                Console.WriteLine($"entry {entry.DistinguishedName}");
                Console.WriteLine($"entry {entry.GetHashCode()}");

                foreach (var name in entry.Attributes.AttributeNames)
                {
                    Console.WriteLine($"Attributes Names ->{name}");
                }

                foreach (DirectoryAttribute value in entry.Attributes.Values)
                {
                    Console.WriteLine($"Attributes Values ->{value}");
                }
            }

        }
            
        catch (LdapException e)
        {
            Console.WriteLine("\r\nUnable to login:\r\n\t" + e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() 
         + ":" + e.Message);
        }
      }
     }
 }
  • perhaps this can help you: https://stackoverflow.com/questions/11561689/using-c-sharp-to-authenticate-user-against-ldap – Roman Jun 24 '22 at 13:21

0 Answers0