c++ - LDAP 的 ldap_search_s() 在 Windows Active Directory 上失败

标签 c++ c windows active-directory ldap

我在 Windows 2008 服务器上设置了 Active Directory 服务。 我添加了一个用户,这是 DN (DistingushedName) CN=ashwin,CN=Users,DC=test,DC=com

没有为 DN 设置密码,允许匿名绑定(bind)。我有一个连接到 AD 并搜索用户的示例(测试代码)C++ 程序。

#include "windows.h"
#include "winldap.h"
#include "stdio.h"

//  Entry point for your application
int main(int argc, char* argv[])
{
    LDAP* pLdapConnection = NULL;
    INT returnCode = 0; 
    INT connectSuccess = 0;
    ULONG version = LDAP_VERSION3;
    LONG lv = 0;
    int option(0);
    LDAPMessage *vLdapMessage;

    //  Initialize an LDAP session without SSL.
    pLdapConnection = ldap_init("192.168.56.128",389);
    if (pLdapConnection == NULL)
    {
        printf( "ldap_init failed with 0x%x.\n",hr);
        return -1;
    }

    //  Specify version 3; the default is version 2.
    returnCode = ldap_set_option(pLdapConnection,
        LDAP_OPT_PROTOCOL_VERSION,
        (void*)&version);
    if (returnCode != LDAP_SUCCESS)
        goto FatalExit;

    //Turning off referrals
    ldap_set_option(pLdapConnection, LDAP_OPT_REFERRALS, LDAP_OPT_OFF); // required 

    //  Connect to the server.
    connectSuccess = ldap_connect(pLdapConnection, NULL);

    if(connectSuccess != LDAP_SUCCESS)
    {
        printf("ldap_connect failed with 0x%x.\n",connectSuccess);
        goto FatalExit;
    }

    //  Bind with current credentials. 
    printf("Binding ...\n");
    returnCode = ldap_bind_s(pLdapConnection,NULL, NULL, LDAP_AUTH_SIMPLE);
    if (returnCode != LDAP_SUCCESS)
        goto FatalExit;

    returnCode = ldap_search_s(pLdapConnection, "DC=test, DC=com", LDAP_SCOPE_SUBTREE, "CN=ashwin", NULL, 0, &vLdapMessage);

    if (returnCode != LDAP_SUCCESS)
        goto FatalExit;

NormalExit:
    if (pLdapConnection != NULL)
        ldap_unbind_s(pLdapConnection);
    return 0;

FatalExit:
    if( pLdapConnection != NULL )
        ldap_unbind_s(pLdapConnection);
    printf( "\n\nERROR: 0x%x\n", returnCode);
    return returnCode;
}

搜索失败。 ldap_search_s 始终返回 1。 在 Apache 目录服务上进行的相同设置测试工作正常。

有人能指出为什么这不适用于 Windows AD 吗?程序有什么问题?

最佳答案

Active Directory 过滤语法可能非常冗长。据我所知,您只需要稍微修改一下过滤器即可。试试这个:

(&(objectClass=user)(distinguishedName=CN=ashwin,CN=Users,DC=test,DC=com))

但是,对于单用户过滤,我会尝试使用 sAMAccountName。这通常遵循 {FirstInitial}{LastName} 格式,并且对用户来说是唯一的(例如 JSmith):

(&(objectClass=user)(sAMAccountName=JSmith))

关于c++ - LDAP 的 ldap_search_s() 在 Windows Active Directory 上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17169964/

相关文章:

windows - 在 Windows 批处理文件中寻找 Unix 风格的 'getopt' 命令行解析

windows - 在 Windows 上使用 LLVM 作为编译器后端 - 需要外部工具吗?

windows - 合并时批处理文件不会运行(在批处理文件中退出 ghostscript

在内存中修改自身的 C++ 对象

c - 在c中的一行中输入字符和整数从过去的输入流中读取字符

c++ - Linux 链接器/加载器的环境覆盖

c - ptr*** 不工作

c++ - Valgrind 在 std::make_unique 中显示内存泄漏

c++ - 嵌入 Pane 时启用\禁用 CMFCToolBar 按钮

c++ - 生成给定集合的子集