C# 针对Active Directory的SimpleBind身份验证
我正在尝试使用以下代码对Active Directory(AD DS)的登录凭据进行身份验证:C# 针对Active Directory的SimpleBind身份验证,c#,asp.net,authentication,active-directory,ldap,C#,Asp.net,Authentication,Active Directory,Ldap,我正在尝试使用以下代码对Active Directory(AD DS)的登录凭据进行身份验证: using (var context = new PrincipalContext(ContextType.Domain, ipAddress)) { Console.WriteLine("Connected to {0}:", context.ConnectedServer); context.ValidateCredentials(username, password); } u
using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
Console.WriteLine("Connected to {0}:", context.ConnectedServer);
context.ValidateCredentials(username, password);
}
using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
// NOTE! Username must be of the format domain\username
return context.ValidateCredentials("domain\someuser", password, ContextOptions.SimpleBind);
}
其中ipAddress是主域控制器的地址。但是,尝试读取上下文时会出现以下错误。ConnectedServer
:
System.DirectoryServices.DirectoryServicesCOMException(0x8007052E):
用户名或密码不正确
除此之外,我还有以下限制:
- 生产环境可能在域上,也可能不在域上
- 客户端不希望输入任何特权凭据来查询目录
using (var context = new PrincipalContext(ContextType.Domain,
ipAddress,
null,
ContextOptions.SimpleBind,
usernameToValidate,
password))
基于这些限制,我如何根据Active Directory进行身份验证?我能够使用以下代码进行身份验证:
using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
Console.WriteLine("Connected to {0}:", context.ConnectedServer);
context.ValidateCredentials(username, password);
}
using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
// NOTE! Username must be of the format domain\username
return context.ValidateCredentials("domain\someuser", password, ContextOptions.SimpleBind);
}
关键部分是在用户名前面加上短域名。一旦我这样做了,并且在调用
ValidateCredentials
而不是在上下文构造函数中指定了SimpleBind,它就工作得很好了。用户名的格式是什么?仅sAMAccountName。如果我使用SimpleBind调用ValidateCredentials,则使用域名前缀是有效的。在调用中设置SimpleBind与在上下文中设置SimpleBind有什么区别?