LDAP 身份验证 windows账号 登录
using System.DirectoryServices;
using System.Runtime.Versioning;
internal class Program
{
private static void Main(string[] args)
{
Program program = new Program();
// 检查当前操作系统是否为 Windows
if (!OperatingSystem.IsWindows())
{
Console.WriteLine("此功能仅支持 Windows 操作系统。");
return;
}
User? user = program.Login("xxxx", "xxxx");
if (user == null)
return;
System.Console.WriteLine(user.DisplayName);
System.Console.WriteLine(user.UserName);
}
[SupportedOSPlatform("windows")]
public User? Login(string userName, string password)
{
try
{
const string DisplayNameAttribute = "DisplayName";
const string SAMAccountNameAttribute = "SAMAccountName";
using DirectoryEntry entry =
new("LDAP://xxxx.com.cn", userName.Trim(), password.Trim());
using DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = String.Format("({0}={1})", SAMAccountNameAttribute, userName);
searcher.PropertiesToLoad.Add(DisplayNameAttribute);
searcher.PropertiesToLoad.Add(SAMAccountNameAttribute);
var result = searcher.FindOne();
if (result != null)
{
var displayName = result.Properties[DisplayNameAttribute];
var samAccountName = result.Properties[SAMAccountNameAttribute];
return new User
{
DisplayName =
displayName == null || displayName.Count <= 0
? null
: displayName[0].ToString(),
UserName =
samAccountName == null || samAccountName.Count <= 0
? null
: samAccountName[0].ToString()
};
}
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
return null;
}
return null;
}
}
public class User
{
public string? UserName { get; set; }
public string? DisplayName { get; set; }
}