使用LdapConnection枚举AD

时间:2012-02-02 23:56:42

标签: c# active-directory ldap directoryservices

是否可以使用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,ldapServer在创建Principal时附加了:636上下文。

我连接的服务器有证书问题,我想这可能会阻止这一点,因为LdapConnection设置为返回true进行验证。这不是问题,因为它是值得信赖的。我无法访问服务器,因此无法更改此内容。

2 个答案:

答案 0 :(得分:2)

据我所知,当您定位域时,容器参数不能为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);

答案 1 :(得分:0)

我怀疑您在LDAP代码中遇到的部分问题是您正在使用AuthType.Basic。请尝试使用Negotiate