首页 > 解决方案 > 在 ldapjs 中搜索

问题描述

我正在尝试在我的 node.js 代码中使用 Ldap.js 的搜索方法。这是我的客户端代码。它成功添加了一个用户,但搜索新添加的用户不会产生任何结果。(ldap 服务器在来自https://github.com/osixia/docker-openldap的 docker 容器中运行)

var ldap = require("ldapjs");
var assert = require("assert");

var client = ldap.createClient({
  url: "ldap://localhost:389",
});

client.bind("cn=admin,dc=example,dc=org", "admin", function (err) {
  assert.ifError(err);
  let newUser = {
    cn: "userId7",
    userPassword: "password",
    objectClass: "person",
    sn: "efub",
  };
  // Here i successfully add this user "userId7"
  client.add(
    "cn=userId7,dc=example,dc=org",
    newUser,
    (err, response) => {
      if (err) return console.log(err);
      return response;
    }
  );

  var options = {
    filter: "(objectClass=*)",
    scope: "sub",
  };
  // Now the search, it runs without error, but does never receive a searchEntry
  client.search(
    "cn=userId7,dc=example,dc=org",
    options,
    function (error, search) {
      console.log("Searching.....");

      client.on("searchEntry", function (entry) {
        console.log("I found a result in searchEntry");
      });

      client.on("error", function (error) {
        console.error("error: " + error.message);
      });

      client.unbind(function (error) {
        if (error) {
          console.log(error.message);
        } else {
          console.log("client disconnected");
        }
      });
    }
  );
});

client.on('error', function (err) {
  if (err.syscall == "connect") {
    console.log(err);
  }
});

另外,如果有帮助,这就是我通过运行显示来自 ldap 的所有用户时新添加的用户的样子docker exec my-openldap-container ldapsearch -x -H ldap://localhost:389 -b dc=example,dc=org -D "cn=admin,dc=example,dc=org" -w admin

# userId7, example.org
dn: cn=userId7,dc=example,dc=org
cn: userId7
userPassword:: cGFzc3dvcmQ=
objectClass: person
sn: efub

更新:我可以使用 shell 命令成功搜索用户“userId7” docker exec ldap-service ldapsearch -LLL -x -D "cn=admin,dc=example,dc=org" -w "admin" -b "cn=userId7,dc=example,dc=org" "(objectclass=*)":. 我怎样才能让 ldapJS 也成功运行这个搜索?

更新 2:我还可以使用前端“phpLDAPadmin”成功搜索,如下面的屏幕截图所示: 搜索掩码 搜索结果

标签: javascriptnode.jsldapopenldapldapjs

解决方案


所以我解决了。正确的client.search代码是:

  client.search(
    "cn=userId7,dc=example,dc=org",
    options,
    function (error, res) {
      console.log("Searching.....");

      res.on("searchEntry", function (entry) {
        console.log("I found a result in searchEntry", JSON.stringify(entry.object));
      });

      res.on("error", function (error) {
        console.error("error: " + error.message);
      });

      client.unbind(function (error) {
        if (error) {
          console.log(error.message);
        } else {
          console.log("client disconnected");
        }
      });
    }
  );

在里面,我通过, 而不是function (error, res) {监听事件,因此从搜索结果中丢失了事件。根本原因是经典的复制和粘贴错误,并在误解事件起源的同时更改了变量。client.on("searchEntry"res.on("searchEntry"


推荐阅读