HRM-10/HRM.DA/Service/LDAPService/LdapAuthService.cs

344 lines
12 KiB
C#
Raw Permalink Normal View History

2026-11-03 13:06:00 +06:00
using HRM.BO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace HRM.DA
{
public class LDAPAuthService
{
private readonly string _ldapServer;
private readonly int _ldapPort;
private readonly string _domainComponents;
private readonly string _defaultDomain;
private readonly string _masterDomain;
private readonly string _baseDN;
private readonly string _domain;
private readonly ILogger<LDAPAuthService> _logger;
public LDAPAuthService(IConfiguration configuration, ILogger<LDAPAuthService> logger)
{
_logger = logger;
_ldapServer = configuration.GetSection("LDAPSettings")["ADServer"];
_ldapPort = Convert.ToInt32(configuration.GetSection("LDAPSettings")["ADServerPort"]);
_masterDomain = configuration.GetSection("LDAPSettings")["MasterDomain"];
_defaultDomain = configuration.GetSection("LDAPSettings")["Domain"];
_baseDN = configuration.GetSection("LDAPSettings")["BaseDN"];
_domain = _defaultDomain;
_domainComponents = string.Join(",", _domain.Split('.').Select(x => $"DC={x}"));
}
private void WriteToFile(string text)
{
string pathDate = DateTime.Today.ToString("dd-MM-yyyy");
string path = "C:\\Log\\Validate_ADLogin " + pathDate + ".txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
public bool ValidateUser(string username, string password)
{
try
{
#region OLD
//string adLoginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
//string normalizedUsername = NormalizeUsername(username);
//using var ldap = new LdapConnection(new LdapDirectoryIdentifier(_ldapServer, _ldapPort));
//var networkCredential = new NetworkCredential(normalizedUsername, password);
//if (_ldapPort == 636)
//{
// ldap.SessionOptions.SecureSocketLayer = true;
//}
//ldap.AuthType = AuthType.Negotiate;
//ldap.Bind(networkCredential);
//return true;
#endregion
#region NEW
username = NormalizeUsername(username);
using var ldap = CreateLdapConnection();
ldap.Bind(new NetworkCredential(username, password));
return true;
#endregion
}
catch (LdapException ex)
{
if (ex.Message.Contains("data 773"))
throw new Exception("PASSWORD_RESET_REQUIRED");
if (ex.Message.Contains("data 532"))
throw new Exception("PASSWORD_EXPIRED");
return false;
}
catch
{
// If any exception occurs, authentication failed
return false;
}
}
public string ValidateUserAndGetADLoginID(string username, string password)
{
string adLoginID = "";
try
{
#region OLD
//string adLoginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
//adLoginID = "";
//string normalizedUsername = NormalizeUsername(username);
//string normalizedUserEmail = NormalizeUserEmail(username);
//using var ldap = new LdapConnection(new LdapDirectoryIdentifier(_ldapServer, _ldapPort));
//var networkCredential = new NetworkCredential(normalizedUsername, password);
//if (_ldapPort == 636)
//{
// ldap.SessionOptions.SecureSocketLayer = true;
//}
//ldap.AuthType = AuthType.Negotiate;
//ldap.Bind(networkCredential);
//adLoginID = normalizedUserEmail;
//return adLoginID;
#endregion
#region NEW
WriteToFile($"LDAP Login Attempt Started for User: {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> UserName: {username}");
if (string.IsNullOrWhiteSpace(username))
throw new Exception("Username cannot be empty.");
if (string.IsNullOrWhiteSpace(password))
throw new Exception("Password cannot be empty.");
string normalizedUsername = NormalizeUsername(username);
WriteToFile($"Normalize User Name: {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> NormalizedUsername: {normalizedUsername}");
using var ldap = CreateLdapConnection();
ldap.Bind(new NetworkCredential(normalizedUsername, password));
WriteToFile($"LDAP Bind Successful for User (User can find in AD): {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> USER: {normalizedUsername}");
#region User Search (Commented Out)
//var searchRequest = new SearchRequest(
// _baseDN,
// $"(sAMAccountName={username})",
// SearchScope.Subtree,
// "sAMAccountName"
//);
//WriteToFile($"Find User with Base DN: {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> BaseDN: {_baseDN}");
//WriteToFile($"Find User with sAMAccountName : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> BaseDN: {username}");
//var response = (SearchResponse)ldap.SendRequest(searchRequest);
//if (response.Entries.Count == 0)
//{
// WriteToFile($"User Not Found : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> User not found in Active Directory.");
// throw new Exception("User not found in Active Directory.");
//}
//else
//{
// WriteToFile($"User Found Successfully : {DateTime.Now:dd-MMM-yyyy HH:mm:ss}");
//}
#endregion
return normalizedUsername;
#endregion
}
catch (LdapException ex)
{
if (ex.Message.Contains("52e"))
{
WriteToFile($"\nError : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> {ex.Message}");
throw new Exception("Invalid password. Please try again.");
}
if (ex.Message.Contains("773"))
{
WriteToFile($"\nError : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> {ex.Message}");
throw new Exception("Password reset required. Please reset your password.");
}
if (ex.Message.Contains("532"))
{
WriteToFile($"\nError : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> {ex.Message}");
throw new Exception("Password expired. Please reset your password.");
}
WriteToFile($"\nError : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> {ex.Message}");
throw new Exception($"LDAP authentication failed: {ex.Message}");
}
catch (Exception ex)
{
WriteToFile($"\nError : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> {ex.Message}");
throw new Exception(ex.Message);
}
}
public ADUserInfo ValidateAndGetUser(string username, string password)
{
try
{
#region OLD
//string normalizedUsername = NormalizeUsername(username);
//using var ldap = new LdapConnection(new LdapDirectoryIdentifier(_ldapServer, _ldapPort));
//if (_ldapPort == 636)
//{
// ldap.SessionOptions.SecureSocketLayer = true;
//}
//ldap.AuthType = AuthType.Negotiate;
//ldap.Bind(new NetworkCredential(normalizedUsername, password));
//string sam = GetSamAccountName(normalizedUsername);
//var searchRequest = new SearchRequest(
// _domainComponents,
// $"(sAMAccountName={sam})",
// SearchScope.Subtree,
// new[] { "displayName", "mail", "memberOf", "userPrincipalName" }
//);
//var response = (SearchResponse)ldap.SendRequest(searchRequest);
//if (response.Entries.Count == 0)
// return null;
//var entry = response.Entries[0];
//var userInfo = new ADUserInfo
//{
// Username = username,
// DisplayName = entry.Attributes["displayName"]?[0]?.ToString(),
// ADLoginID = normalizedUsername,
// //Email = entry.Attributes["mail"]?[0]?.ToString()
// Email = entry.Attributes["mail"]?[0]?.ToString() ?? entry.Attributes["userPrincipalName"]?[0]?.ToString()
//};
//if (entry.Attributes["memberOf"] != null)
//{
// foreach (var group in entry.Attributes["memberOf"])
// userInfo.Groups.Add(group.ToString());
//}
//return userInfo;
#endregion
#region NEW
if (string.IsNullOrWhiteSpace(username))
throw new Exception("Username cannot be empty.");
if (string.IsNullOrWhiteSpace(password))
throw new Exception("Password cannot be empty.");
username = NormalizeUsername(username);
using var ldap = CreateLdapConnection();
ldap.Bind(new NetworkCredential(username, password));
var searchRequest = new SearchRequest(
_baseDN,
$"(sAMAccountName={username})",
SearchScope.Subtree,
"displayName",
"mail",
"sAMAccountName",
"title",
"department"
);
var response = (SearchResponse)ldap.SendRequest(searchRequest);
if (response.Entries.Count == 0)
throw new Exception("User not found in Active Directory.");
var entry = response.Entries[0];
return new ADUserInfo
{
FullName = entry.Attributes["displayName"]?[0]?.ToString(),
Email = entry.Attributes["mail"]?[0]?.ToString(),
LoginID = entry.Attributes["sAMAccountName"]?[0]?.ToString(),
Designation = entry.Attributes["title"]?[0]?.ToString(),
Department = entry.Attributes["department"]?[0]?.ToString(),
};
#endregion
}
catch (LdapException ex)
{
if (ex.Message.Contains("52e"))
throw new Exception("Invalid password. Please try again.");
if (ex.Message.Contains("773"))
throw new Exception("Password reset required. Please reset your password.");
if (ex.Message.Contains("532"))
throw new Exception("Password expired. Please reset your password.");
throw new Exception($"LDAP authentication failed: {ex.Message}");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private LdapConnection CreateLdapConnection()
{
try
{
WriteToFile($"LDAP Connection Starting : {DateTime.Now:dd-MMM-yyyy HH:mm:ss} -> Server: {_ldapServer}, Port: {_ldapPort}");
var identifier = new LdapDirectoryIdentifier(_ldapServer, _ldapPort, true, false);
var ldap = new LdapConnection(identifier);
ldap.SessionOptions.ProtocolVersion = 3;
ldap.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
ldap.Timeout = TimeSpan.FromSeconds(10);
WriteToFile($"LDAP Connection Object Created Successfully : {DateTime.Now:dd-MMM-yyyy HH:mm:ss}");
if (_ldapPort == 636)
{
ldap.SessionOptions.SecureSocketLayer = true;
ldap.SessionOptions.VerifyServerCertificate += (conn, cert) => true;
_logger.LogInformation("LDAP Secure SSL Enabled (Port 636)");
WriteToFile($"LDAP Secure SSL Enabled (Port 636) : {DateTime.Now:dd-MMM-yyyy HH:mm:ss}");
}
else
{
WriteToFile($"LDAP Running Without SSL (Port): {_ldapPort}) : {DateTime.Now:dd-MMM-yyyy HH:mm:ss}");
}
return ldap;
}
catch (Exception ex)
{
WriteToFile($"LDAP Connection Creation Failed -> Server: {_ldapServer}, Port: {_ldapPort} : {DateTime.Now:dd-MMM-yyyy HH:mm:ss}");
throw;
}
}
private string NormalizeUsername(string username)
{
// Normalize username format:
// - If "user@domain.com" -> return as is
// - If "DOMAIN\user" -> return as is
// - If plain "user" -> append default domain (user@grameenphone.com)
if (string.IsNullOrEmpty(username)) return username;
if (username.Contains("@")) return username;
if (username.Contains("\\")) return username;
return $"{username}@{_defaultDomain}";
}
private string NormalizeUserEmail(string username)
{
return $"{username}@{_masterDomain}";
}
private string GetSamAccountName(string username)
{
// Extract plain sAMAccountName (Windows login name):
// - From "user@domain.com" -> "user"
// - From "DOMAIN\user" -> "user"
// - From plain "user" -> "user"
if (string.IsNullOrEmpty(username)) return username;
if (username.Contains("@"))
return username.Split('@')[0];
if (username.Contains("\\"))
return username.Substring(username.IndexOf('\\') + 1);
return username;
}
}
public class ADUserInfo
{
public string FullName { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
public string LoginID { get; set; }
public string Designation { get; set; }
public string Department { get; set; }
public List<string> Groups { get; set; } = new List<string>();
}
}