uid (簡稱) 屬性,需手動新增。使用輸入的帳號密碼建立 DirectoryEntry 進行 LDAP 繫結查詢,**若不拋出例外則驗證通過**。
using System.DirectoryServices;
using System.Configuration;
public class LDAPHelper
{
public string DominoServer { get; set; }
public string LdapServer { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public LDAPHelper(string userName, string passWord)
{
LdapServer = "LDAP://192.176.0.46"; // 實際 IP
DominoServer = "192.176.0.46";
UserName = userName;
PassWord = passWord;
}
public bool VerifyUser()
{
try
{
var searcher = PrepareSearcher();
var result = searcher.FindOne(); // 繫結並查詢
return result != null;
}
catch
{
return false;
}
}
private DirectorySearcher PrepareSearcher()
{
var root = new DirectoryEntry(LdapServer, UserName, PassWord, AuthenticationTypes.None);
var searcher = new DirectorySearcher(root);
// 過濾條件:dominoPerson 且 (cn=帳號 OR uid=簡稱 OR mail=Email)
searcher.Filter = $"(&(objectClass=dominoPerson)(|(cn={UserName})(uid={UserName})(mail={UserName})))";
return searcher;
}
}
var ldap = new LDAPHelper("userName", "password");
if (ldap.VerifyUser())
Console.WriteLine("驗證成功");
else
Console.WriteLine("帳號或密碼錯誤");
AuthenticationTypes.None 表示簡單繫結 (明文傳輸),生產環境建議使用 SSL/LDAPS (LDAPS://) 或 AuthenticationTypes.Secure。cn (完整名稱)、uid (簡稱)、mail (Email) 三種登入方式。catch,實際專案建議細分 DirectoryServicesCOMException 等具體例外處理。