Click here to Skip to main content
15,885,032 members
Articles / Web Development / ASP.NET / ASP.NET Core
Tip/Trick

C#: Validate a username and password from LDAP

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
15 Jul 2020CPOL1 min read 34.7K   671   12   2
Username and password validation process from LDAP server in ASP.NET and ASP.NET Core
This is a simple post to demonstrate the username and password validation process from LDAP server in ASP.NET and ASP.NET Core using C#.

ASP.NET

We need to add System.DirectoryServices DLL reference in our project. In packages.config file, we can add the below package or install it using NuGet.

XML
<packages>
  <package id="System.DirectoryServices" version="4.7.0" targetFramework="net461" />
</packages>

Here is the manager class, Validate(string userId, string password) method will validate things from LDAP server.

C#
/*
 * Links:
 * https://www.nuget.org/packages/System.DirectoryServices/
 */
using System.DirectoryServices;

namespace DotNet
{
    /// <summary>
    /// Ldap related contracts
    /// </summary>
    public interface ILdapValidator
    {
        /// <summary>
        /// Check if user in Ldap 
        /// </summary>
        /// <param name="userId">Ldap user name without domain name</param>
        /// <param name="password">Ldap passsword</param>
        bool Validate(string userId, string password);
    }

    /// <summary>
    /// Ldap related tasks manager
    /// </summary>
    public class LdapManager : ILdapValidator
    {
        /// <summary>
        /// Domain name from config file
        /// </summary>
        public readonly string DomainName;
        /// <summary>
        /// Port name form config file, default 389
        /// </summary>
        public readonly int PortNumber;

        public LdapManager(string domainName, int port = 389)
        {
            DomainName = domainName;
            PortNumber = port;
        }

        /// <summary>
        /// Check if user in Ldap 
        /// </summary>
        /// <param name="userId">Ldap user name without domain name</param>
        /// <param name="password">Ldap passsword</param>
        public bool Validate(string userId, string password)
        {
            try
            {
                string path = LdapPath();
                string username = UserFullId(userId);
                DirectoryEntry de = new DirectoryEntry
                         (path, username, password, AuthenticationTypes.Secure);
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.FindOne();
                return true;
            }
            catch (DirectoryServicesCOMException ex)
            {
                return false;
            }
        }

        /// <summary>
        /// User full id 
        /// </summary>
        /// <param name="userId">User name</param>
        /// <returns>userName@domain</returns>
        public string UserFullId(string userId)
        {
            string value = string.Format(@"{0}@{1}", userId, DomainName);
            return value;
        }

        /// <summary>
        /// Get Ldap path from domain and port
        /// </summary>
        /// <returns></returns>
        public string LdapPath()
        {
            string value = string.Format(@"LDAP://{0}:{1}", DomainName, PortNumber);
            return value;
        }
    }
}

Here, we are using the LDAP manager class to validate username and password:

C#
string domain = "LdapdomainNameOrIp.com";
int port = 389;
string user = "user.name";
string password = "password@123";
bool isValied = new LdapManager(domain, port).Validate(user, password);

ASP.NET Core

We need to add Novell.Directory.Ldap DLL reference in our project. In .csproj file, we can add the below package or install it from NuGet.

XML
<ItemGroup>
  <PackageReference Include="Novell.Directory.Ldap.NETStandard" Version="2.3.8" />
</ItemGroup>

Here is the manager class, Validate(string userId, string password) method will validate things from LDAP server.

C#
/*
 * Links:
 * https://www.nuget.org/packages/Novell.Directory.Ldap.NETStandard/2.3.8
*/

using Novell.Directory.Ldap;
using System;

namespace DotNetCore
{
    /// <summary>
    /// Ldap related contracts
    /// </summary>
    public interface ILdapValidator
    {
        /// <summary>
        /// Check if user in Ldap 
        /// </summary>
        /// <param name="userId">Ldap user name without domain name</param>
        /// <param name="password">Ldap passsword</param>
        bool Validate(string userId, string password);
    }

    /// <summary>
    /// Ldap related tasks manager
    /// </summary>
    public class LdapManager : ILdapValidator
    {
        /// <summary>
        /// Domain name from config file
        /// </summary>
        public readonly string DomainName;
        /// <summary>
        /// Port name form config file, default 389
        /// </summary>
        public readonly int PortNumber;

        public LdapManager(string domainName, int port = 389)
        {
            DomainName = domainName;
            PortNumber = port;      /*LdapConnection.DEFAULT_PORT*/
        }

        /// <summary>
        /// Check if user in Ldap 
        /// </summary>
        /// <param name="userId">Ldap user name without domain name</param>
        /// <param name="password">Ldap passsword</param>
        public bool Validate(string userId, string password)
        {
            try
            {
                string username = UserFullId(userId);  
                using (var connection = new LdapConnection { SecureSocketLayer = false })
                {
                    connection.Connect(DomainName, PortNumber);
                    connection.Bind(username, password);
                    return connection.Bound;
                }
            }
            catch (LdapException ex)
            {
                return false;
            }
        }

        /// <summary>
        /// User full id 
        /// </summary>
        /// <param name="userId">User name</param>
        /// <returns>userName@domain</returns>
        public string UserFullId(string userId)
        {
            string value = string.Format(@"{0}@{1}", userId, DomainName);
            return value;
        }
    }
}

Here, we are using the LDAP manager class to validate username and password:

C#
string domain = "LdapdomainNameOrIp.com";
int port = 389;
string user = "user.name";
string password = "password@123";
bool isValied = new LdapManager(domain, port).Validate(user, password);

Source Code

It is a Visual Studio 2017 solution with console projects:

  • DotNet: .NET Framework 4.6.1
  • DotNetCore: .NET Core 2.2

References

Limitations

  • The LDAP path may not be simple as mine so fix it as needed.
  • The code may throw an error for untested inputs, if may please let me know

History

  • 15th July, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThanks Dipon. Really Simple and Neat example. Pin
Member 1218063131-Aug-21 23:27
Member 1218063131-Aug-21 23:27 
GeneralRe: Thanks Dipon. Really Simple and Neat example. Pin
DiponRoy2-Sep-21 17:58
DiponRoy2-Sep-21 17:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.