.NET 藉由 LDAP 驗證 AD 使用者的帳號與密碼 (Validate AD User With LDAP)


  1. 說明
  2. 參考資料

筆記 .NET 如何透過 LDAP 驗證 AD 使用者的帳號與密碼是否正確。

logo

說明

static void Main(string[] args)
{
    string _path = "ldap://10.0.0.1";
    string EmpId = "adUserName";
    string Password = "adPassword";

    DirectoryEntry User = ValidateUser(_path, EmpId, Password);

    if (User != null)
    {
        Console.WriteLine($"{EmpId} 驗證成功");
    }
    else
    {
        Console.WriteLine($"帳戶不存在或密碼驗證失敗 ");
    }
}

藉由建立 DirectoryServices Namespace 下的 DirectoryEntry,建立時必須以 Ldap Service 的 IP 以及 AD User Name 與 Password 作為參數,如果可以成功建立並可以藉由 SecurityIdentifier 取得該 Entry 的 SID 就屬於建立成功。

using System.DirectoryServices;
using System.Security.Principal;

public static DirectoryEntry ValidateUser(
  string LDAPService, string UserName, string Password)
{
    DirectoryEntry entry = new DirectoryEntry(LDAPService, UserName, Password);

    try
    {
        string objectSid = (new SecurityIdentifier(
          (byte[])entry.Properties["objectSid"].Value, 0).Value);
        Console.WriteLine(objectSid);
        return entry;
    }
    catch
    {
        return null;
    }
    finally
    {
        entry.Dispose();
    }
}

參考資料