Skip to content

Instantly share code, notes, and snippets.

@dzitkowskik
Last active January 11, 2024 09:07
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dzitkowskik/279164c1343e652660dc to your computer and use it in GitHub Desktop.
Save dzitkowskik/279164c1343e652660dc to your computer and use it in GitHub Desktop.
How to authenticate user in Ldap / OpenLdap using C# (user: test in domain ghashd.servebeer.com, server on ip 192.168.0.12 port 389)
using System;
using System.Net;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Security.Permissions;
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("192.168.0.12", 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=testa,ou=people,dc=ghashd,dc=servebeer,dc=com",
"zaq12wsx"); //password
ldapConnection.Bind(nc);
Console.WriteLine("LdapConnection authentication success");
ldapConnection.Dispose();
}
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);
}
}
}
}
@geomorillo
Copy link

works perfectly ... i wasnt able to connect with other methods thanks

@db199615
Copy link

works well but i have one one doubt..you are using 192.168.0.12 server...is this is a free online ldap server?? how can i get other user details in this?? since i am very new to this concept ..it makes me difficult to understand..
i had used online ldap.forumsys.com ...but it doesnt work..
please help me..
Thanks in advance..

@will7200
Copy link

No that is on LAN, 192.168.. is used for private networks.

@Github743
Copy link

What should be replaced ("192.168.0.12", 389) for these

@raminkarimkhani1996
Copy link

how can i create new user with LDAP

@ahmad-moussawi
Copy link

For those who asking how to create an LDAP server, there are multiple options here:

  1. use OpenLDAP an open-source server implementation of the LDAP protocol, you can download a running docker image from https://github.com/osixia/docker-openldap
  2. use Apache Directory Studio includes Apache DS also another implementation in Java (this is the easiest option) https://directory.apache.org/studio/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment