我为Active Directory LDAP用户的身份验证编写了代码。它对AD中的所有用户帐户进行身份验证,但我只想要管理员帐户身份验证而不是其他用户帐户(请参阅下面的代码)。还可以找到连接DNS的域名(请参阅附图)。
try
{
DirectoryEntry entry = new DirectoryEntry(Domain, UserName, Password);
object nativeObject = entry.NativeObject;
Program.fileWrite.WriteLine(DateTime.Now + "\t Login with credentials " + UserName + " and " + Password);
return true;
}
catch (DirectoryServicesCOMException e)
{
Program.fileWrite.WriteLine(DateTime.Now + "\t " + e.Message);
return false;
}
答案 0 :(得分:2)
试试这段代码:
public static bool ValidateCredential(string domain, string userName, string password)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
{
if (user == null) return false;
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Admins"))
{
if (group == null) return false;
foreach (var member in group.GetMembers())
{
if (member.Sid.Equals(user.Sid))
{
return context.ValidateCredentials(userName, password);
}
}
}
}
}
return false;
}