LdapConnection与PrincipalContext

DTI*_*att 7 .net c# ssl ldap active-directory

我有以下两种使用LDAP和LDAPS验证用户的实现,我想知道哪个更好/更正确.对于记录,这两个都适用于SSL和非SSL连接.

我也很好奇,因为使用Wireshark于观看时Non-SSL PrincipalContext的版本,我仍然看到交通上的端口636的四种组合(Non-SSL LdapConnection,SSL LdapConnection,Non-SSL PrincipalContext,SSL PrincipalContext)它是唯一一个有两个端口389的流量和636而不是一个或另一个.可能是什么导致了这个?

LDAP连接方法:

bool userAuthenticated = false;
var domainName = DomainName;

if (useSSL)
{
  domainName = domainName + ":636";
}

try
{
  using (var ldap = new LdapConnection(domainName))
  {
    var networkCredential = new NetworkCredential(username, password, domainName);
    ldap.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback((con, cer) => true);
    ldap.SessionOptions.SecureSocketLayer = useSSL;
    ldap.SessionOptions.ProtocolVersion = 3;
    ldap.AuthType = AuthType.Negotiate;
    ldap.Bind(networkCredential);
  }

  // If the bind succeeds, we have a valid user/pass.
  userAuthenticated = true;
}
catch (LdapException ldapEx)
{
  // Error Code 0x31 signifies invalid credentials, anything else will be caught outside.
  if (!ldapEx.ErrorCode.Equals(0x31))
  {
    throw;
  }
}

return userAuthenticated;
Run Code Online (Sandbox Code Playgroud)

PrincipalContext方法:

bool userAuthenticated = false;
var domainName = DomainName;

if (useSSL)
{
  domainName = domainName + ":636";
  ContextOptions options = ContextOptions.SimpleBind | ContextOptions.SecureSocketLayer;

  using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, null, options))
  {
    userAuthenticated = pc.ValidateCredentials(username, password, options);
  }
}
else
{
  using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName))
  {
    userAuthenticated = pc.ValidateCredentials(username, password);
  }
}

return userAuthenticated;
Run Code Online (Sandbox Code Playgroud)

小智 6

@ DTI-Matt,在上面的例子中,你使用VerifyServerCertificate总是返回的回调true.这基本上违反了通过SSL连接到LDAP的目的,因为没有执行真正的证书检查.

虽然您可以使用X509Chain和/或X509Certificate2类实现真正的证书检查,但它似乎会PrincipalContext为您处理检查.

总结一下,通过普通或SSL连接连接LDAP服务器,LdapConnectionPrincipalContext提供非常相似的功能.您必须提供LdapConnection更多手写代码才能正常工作.另一方面,PrincipalContext为您提供相同的功能,手动编写的代码更少.

请注意,非SSL通过端口636(您的默认LDAP over SSL端口)PrincipalContext连接可能是因为此类尝试尽可能安全地连接.