Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C#: Validate a username and password from LDAP

0.00/5 (No votes)
15 Jul 2020 1  
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.

<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.

/*
 * 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:

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.

<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.

/*
 * 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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here