是否可以使用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);


为了完整性,我传入相同的值,用户名采用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);

10-06 12:53