From f1777c7d96ecb36e46b46019cbb76d3bb75928e9 Mon Sep 17 00:00:00 2001 From: Luis Martinez Date: Fri, 22 Dec 2023 16:08:50 -0500 Subject: [PATCH] Ldap login v1 --- Auth/Properties/launchSettings.json | 12 +++ LdapLoginLib/LdapLoginLib.csproj | 14 +++ LdapLoginLib/LdapUser.cs | 103 +++++++++++++++++++++ LdapLoginLib/LoginLib.cs | 133 ++++++++++++++++++++++++++++ 4 files changed, 262 insertions(+) create mode 100644 Auth/Properties/launchSettings.json create mode 100644 LdapLoginLib/LdapLoginLib.csproj create mode 100644 LdapLoginLib/LdapUser.cs create mode 100644 LdapLoginLib/LoginLib.cs diff --git a/Auth/Properties/launchSettings.json b/Auth/Properties/launchSettings.json new file mode 100644 index 0000000..408ce4f --- /dev/null +++ b/Auth/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "Auth": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:58174;http://localhost:58175" + } + } +} \ No newline at end of file diff --git a/LdapLoginLib/LdapLoginLib.csproj b/LdapLoginLib/LdapLoginLib.csproj new file mode 100644 index 0000000..4c2dabd --- /dev/null +++ b/LdapLoginLib/LdapLoginLib.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/LdapLoginLib/LdapUser.cs b/LdapLoginLib/LdapUser.cs new file mode 100644 index 0000000..c5a4fde --- /dev/null +++ b/LdapLoginLib/LdapUser.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LdapLoginLib +{ + public class LdapUser + { + /// + /// The unique identifier for the user (mandatory). + /// Example: "jdoe" + /// + public string Uid { get; set; } + + /// + /// The common name of the user. + /// Example: "John Doe" + /// + public string? Cn { get; set; } + + /// + /// The user's given name. + /// Example: "John" + /// + public string? GivenName { get; set; } + + /// + /// The user's surname. + /// Example: "Doe" + /// + public string? Sn { get; set; } + + /// + /// The user's email address. + /// Example: "jdoe@example.com" + /// + public string? Mail { get; set; } + + /// + /// The status of the user's internet account. + /// Example: "Active" + /// + public string? InetUserStatus { get; set; } + + /// + /// The organization the user belongs to. + /// Example: "Acme Inc.", currently "Sede" + /// + public string? O { get; set; } + + /// + /// The status of the user's account as boolean. + /// Example: true or false + /// + public bool? IsActive { get; set; } = null; + + } + + + /******************************************** + * * + * Discared / not in used * + * * + ******************************************** + + /// + /// The user's password. + /// Example: "P@ssw0rd" + /// + public string? UserPassword { get; set; } + + /// + /// The type of employee (e.g., full-time, part-time). + /// Example: "Full-Time", currently numbers + /// + public string? EmployeeType { get; set; } + + /// + /// The business category of the user. + /// Example: "Sales" + /// + public string? BusinessCategory { get; set; } + + /// + /// The employee's unique identification number. + /// Example: "E12345" + /// + public string? EmployeeNumber { get; set; } + + /// + /// The license information for the user. + /// Example: "Licensed for Software X, Y, and Z" + /// + public string? NsLicensedFor { get; set; } + + + ******************************************** + * * + ********************************************/ + +} diff --git a/LdapLoginLib/LoginLib.cs b/LdapLoginLib/LoginLib.cs new file mode 100644 index 0000000..6f9035f --- /dev/null +++ b/LdapLoginLib/LoginLib.cs @@ -0,0 +1,133 @@ +using System.DirectoryServices.Protocols; + +namespace LdapLoginLib +{ + public class LoginLib + { + private const string _ldapServer = "10.31.3.13"; + private const int _ldapPort = 389; + + private const string _ldapDn = "ou=People,o=unal.edu.co"; //uid=pdocente, + //string ldapPassword = "TJBjzn64"; + + + + public static bool Login(string uid, string password, string ldapDn = _ldapDn) + { + + using (LdapConnection ldapConnection = new($"{_ldapServer}:{_ldapPort}")) + { + try + { + string ldapUserDn = $"uid={uid},{_ldapDn}"; + + // Set LDAP connection options + ldapConnection.SessionOptions.SecureSocketLayer = false; + ldapConnection.AuthType = AuthType.Basic; + ldapConnection.Credential = new System.Net.NetworkCredential(ldapUserDn, password); + + // Attempt to bind (authenticate) the user + ldapConnection.Bind(); + + return _userIsActive(ldapConnection, ldapUserDn); + } + catch (LdapException ldapEx) + { + //Console.WriteLine($"Authentication failed: {ldapEx.Message}"); + throw new Exception(_getErrorMessage(ldapEx.ErrorCode, ldapEx.Message)); + } + catch (Exception ex) + { + //Console.WriteLine($"An error occurred: {ex.Message}"); + throw new Exception($"Ocurrió un error: {ex.Message}"); + } + + } + } + + private static bool _userIsActive(LdapConnection ldapConnection, string ldapUserDn) + { + //ldapUserDn = $"uid=acbuitragoc,{_ldapDn}"; + SearchRequest searchRequest = new( + ldapUserDn, + "(objectClass=*)", + SearchScope.Base, + "InetUserStatus" + ); + + SearchResponse searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest); + + if (searchResponse.Entries.Count > 0) + { + SearchResultEntry entry = searchResponse.Entries[0]; + + string? inetUserStatus = entry.Attributes["inetUserStatus"][0].ToString(); + + if (inetUserStatus != null) + { + return inetUserStatus.ToLower().Trim() == "active" ? true : false; + } + throw new Exception(); + } + else + { + throw new Exception($"Usuario o atributo no encontrado."); + } + } + + + private static LdapUser _getUserData(LdapConnection ldapConnection, string ldapUserDn, string[] attributesToReturn) + { + + return new LdapUser(); + + + //SearchRequest searchRequest = new( + // searchBase, + // ldapFilter, + // SearchScope.Subtree, + // attributesToReturn + //); + + //SearchResponse searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest); + + + //if (searchResponse != null && searchResponse.Entries.Count > 0) + //{ + // SearchResultEntry entry = searchResponse.Entries[0]; + + // // Access and process user attributes here + // foreach (DirectoryAttribute attribute in entry.Attributes.Values) + // { + // string attributeName = attribute.Name; + // string[] attributeValues = (string[])attribute.GetValues(typeof(string)); + + // // Process or display attribute values as needed + // Console.WriteLine($"{attributeName}: {string.Join(", ", attributeValues)}"); + // } + //} + //else + //{ + // throw new Exception($"Usuario o atributos no encontrados."); + //} + } + + + private static string _getErrorMessage(int errorCode, string errorMessage) + { + // Map LDAP error codes to error messages + + switch (errorCode) + { + case 49: + return "Error de credenciales: nombre de usuario o contraseña incorrectos"; + case 52: + return "Error de autenticación: cuenta está deshabilitada"; + case 81: + return "Error de servidor: no disponible"; + default: + return errorMessage; + } + } + } +} \ No newline at end of file