Why is node-ldapauth so slow, even when cached?

2019-06-13 22:45发布

问题:

My simple express.js REST-API does authentication through a company-wide LDAP-server. I'm using trentm's node-ldapauth module

The actual question is: when I use a simple function directly comparing the username and password to provided test-values, responses in the browser are finished in roughly the range of 8 to 15 ms. That includes a call to the MongoDB getting data (not much for this test).

If I use the ldapauth.authenticate function, which does caching ({cache: true}), it takes between 80 and 100ms. From the code I can only see that it checks an LRU-cache, and of course the first request would be slower because it's actually checking the LDAP server, but subsequent ones?

Here's a little snippet from the app:

  process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
  var ldap = new LdapAuth({
    url: config.ldap.url,
    adminDn: config.ldap.adminDn,
    adminPassword: config.ldap.adminPassword,
    searchBase: config.ldap.userBase,
    searchFilter: config.ldap.userFilter,
    cache: true
  });

  app.enable('trust proxy');
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(checkUrl);
  app.use(express.basicAuth(function(user, pass, callback) {
//    if(user === 'samuel' && pass === 'supertest') {
//      callback(null, {name: 'samuel'});
//    } else {
//      callback(new Error("Unauthorized"));
//    }
    ldap.authenticate(user, pass, function(err, user) {
      if(err) {
        console.log("LDAP auth error: %s %s", err, err.dn);
        callback(err);
      }   
      callback(err, user);
    }); 
  }));

Any hints are appreciated.

回答1:

This is because under the covers, node-ldapauth is using bcrypt a cryptographically strong and slow hashing algorithm. You actually WANT this to happen. The slower the hash, the longer it takes a hacker to reverse your hashes. The following link shows you where its used:

https://github.com/trentm/node-ldapauth/blob/master/lib/ldapauth.js#L338

For more on why to use bcrypt checkout this article:

http://codahale.com/how-to-safely-store-a-password/

Of course, some of what the author mentions in that article is widely debated, but the idea behind why you want a slow hashing algorithm is sound.