使用LdapConnection枚举AD
本文关键字:AD 枚举 LdapConnection 使用 | 更新日期: 2023-09-27 18:22:23
是否可以使用System.DirectoryServices.Protocols中的LdapConnection查询Active Directory?
我在实例化PrincipalContext时遇到问题。这是我的代码,以防有人发现问题:
private LdapConnection getLdapConnection(string username, string password, string ldapServer, bool secured)
{
int port = secured ? 636 : 389;
LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(ldapServer, port, false, false));
if (secured)
{
connection.SessionOptions.ProtocolVersion = 3;
connection.SessionOptions.SecureSocketLayer = true;
}
connection.Credential = new NetworkCredential(username, password);
connection.AuthType = AuthType.Basic;
connection.SessionOptions.VerifyServerCertificate += (conn, cert) => { return true; };
connection.Bind();
return connection;
}
当尝试实例化主体上下文时,我正在使用
PrincipalContext context = new PrincipalContext(
ContextType.Domain,
ldapServer,
null,
useSsl ? ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind : ContextOptions.SimpleBind,
username,
password);
我在中传递了相同的值,为了完整起见,username的格式为domain'user
,ldapServer的格式为server.domain.com
,在创建Principal Context时添加了ldapServer:636。
我正在连接的服务器存在证书问题,我想这可能是由于LdapConnection设置为返回true进行验证而导致的。这不是一个值得信赖的问题。我没有访问服务器的权限,因此无法更改此项。
据我所知,当您以域为目标时,容器参数不能是null
。你能试试这个构造函数吗:
PrincipalContext domainContextMonou = new PrincipalContext(ContextType.Domain,
"server.domain.com :389",
"dc=domain,dc=com",
username,
password);
然后这个:
PrincipalContext domainContextMonou = new PrincipalContext(ContextType.Domain,
"server.domain.com :636",
"dc=domain,dc=com",
useSsl ? ContextOptions.SecureSocketLayer | ContextOptions.SimpleBind : ContextOptions.SimpleBind,
username,
password);
我怀疑LDAP代码的部分问题在于您使用的是AuthType.Basic
。请改用Negotiate
。