我有以下两种使用 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;
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;