Click here to Skip to main content
14,599,444 members

C#: Validate a username and password from LDAP

Rate this:
4.00 (3 votes)
Please Sign up or sign in to vote.
4.00 (3 votes)
15 Jul 2020CPOL
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy
Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
Tip/Trick
Posted 15 Jul 2020

Stats

5.2K views
99 downloads
9 bookmarked