mr. Holiday
mr. Holiday

Reputation: 1800

ldapjs connection times out after certain period of time

I have some issues regarding searchEntry in LDAP repository using LDAPjs. I am not very familiar with LDAP and because of that I might be missing something in the client implementation. The problem is that after some period of time LDAP there is no response from LDAP server, just nothing none of the callbacks are invoked.

  const ldapClient = ldap.createClient({
      url: 'ldap://some.ldap.server',
      timeout: 3000,
      connectTimeout: 6000
    });

  ldapClient.search('c=XX', opts, (err, res) => {
    if (err) {
      ldapClient.unbind(function(err) {
        if (err) {
          console.log(err)
        }
      });
      return next(null);
    }
  res.once('searchEntry', (entry) => {
    ldapClient.unbind(function(err) {
      if (err) {
      console.log(err)
      }
    });
    return next(entry);
  });

  res.on('error', (error) => {
    ldapClient.unbind(function(err) {
      if (err) {
      console.log(err)
      }
    });
    return next(null, new Error(error.message));
  });
});

Upvotes: 2

Views: 3379

Answers (1)

aveek
aveek

Reputation: 180

Pass the reconnect flag as true while creating the LDAP client and don't unbind it in the way you have done. I guess it also hinders the reconnection. Unbind it only after successful search operation.

This code works for me: (The values are dummy of course)

var ldap = require('ldapjs');
var tlsOptions = {
    host: 'example.com',
    port: '636',
    ca: [fs.readFileSync('./path/to/cert.pem')]
};
var client = ldap.createClient({
    url: 'ldaps://example.com:636',
    reconnect: true
    tlsOptions: tlsOptions
});

client.bind(username, password, function (err) {
    if (err) {
        console.log('Error occurred while binding');
    } else {
        var base = 'cn=admin,dc=example,dc=com';
        var search_options = {
            scope: 'sub',
            filter: '(&(objectClass=*)(CN=' + username + '))',
            attrs: 'attrs'
        };
        client.search(base, search_options, function (err, res) {
            if (err) {
                console.log('Error occurred while ldap search');
            } else {
                res.on('searchEntry', function (entry) {
                    console.log('Entry', JSON.stringify(entry.object));
                });
                res.on('searchReference', function (referral) {
                    console.log('Referral', referral);
                });
                res.on('error', function (err) {
                    console.log('Error is', err);
                });
                res.on('end', function (result) {
                    console.log('Result is', result);
                });
            }
        });
    }
});

Upvotes: 2

Related Questions