【问题标题】:SimpleBind Authentication against Active Directory针对 Active Directory 的 SimpleBind 身份验证
【发布时间】:2014-03-17 15:51:49
【问题描述】:

我正在尝试使用以下代码针对 Active Directory (AD DS) 验证登录凭据:

using (var context = new PrincipalContext(ContextType.Domain, ipAddress))
{
    Console.WriteLine("Connected to {0}:", context.ConnectedServer);
    context.ValidateCredentials(username, password);
}

其中 ipAddress 是主域控制器的地址。但是,这在尝试读取 context.ConnectedServer 时会出现以下错误:

System.DirectoryServices.DirectoryServicesCOMException (0x8007052E): 用户名或密码不正确。

除了这个问题,我还有以下限制:

  • 生产环境可能在也可能不在域中。

  • 客户端不想输入任何特权凭据来查询目录。

由于第二个限制,我尝试执行 SimpleBind,但运气不佳:

using (var context = new PrincipalContext(ContextType.Domain, 
                                          ipAddress, 
                                          null, 
                                          ContextOptions.SimpleBind, 
                                          usernameToValidate, 
                                          password))

基于这些限制,我如何针对 Active Directory 进行身份验证?

【问题讨论】:

  • 您以何种格式获取用户名?
  • sAMAccountName 仅。如果我使用 SimpleBind 调用 ValidateCredentials,则可以使用域名前缀。在调用中设置 SimpleBind 与在上下文中设置有什么区别?

标签: c# asp.net authentication active-directory ldap


【解决方案1】:

我能够使用以下代码进行身份验证:

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,它就可以正常工作了。

【讨论】: