vesse / node-ldapauth-fork

Simple node.js module to authenticate against an LDAP server
Other
127 stars 79 forks source link

ldapauth-fork

Fork of node-ldapauth - A simple node.js lib to authenticate against an LDAP server.

About the fork

This fork was originally created and published because of an urgent need to get newer version of ldapjs in use to passport-ldapauth since the newer version supported passing tlsOptions to the TLS module. Since then a lot of issues from the original module (#2, #3, #8, #10, #11, #12, #13) have been fixed, and new features have been added as well.

Multiple ldapjs client options have been made available.

Usage

var LdapAuth = require('ldapauth-fork');
var options = {
  url: 'ldaps://ldap.example.org:636',
  ...
};
var auth = new LdapAuth(options);
auth.on('error', function (err) {
  console.error('LdapAuth: ', err);
});
...
auth.authenticate(username, password, function(err, user) { ... });
...
auth.close(function(err) { ... })

LdapAuth inherits from EventEmitter.

Install

npm install ldapauth-fork

LdapAuth Config Options

Required ldapjs client options:

ldapauth-fork options:

ldapauth-fork can look for valid users groups too. Related options:

Other ldapauth-fork options:

Optional ldapjs options, see ldapjs documentation:

How it works

The LDAP authentication flow is usually:

  1. Bind the admin client using the given bindDN and bindCredentials
  2. Use the admin client to search for the user by substituting {{username}} from the searchFilter with given username
  3. If user is found, verify the given password by trying to bind the user client with the found LDAP user object and given password
  4. If password was correct and group search options were provided, search for the groups of the user

express/connect basicAuth example

var basicAuth = require('basic-auth');
var LdapAuth = require('ldapauth-fork');

var ldap = new LdapAuth({
  url: 'ldaps://ldap.example.org:636',
  bindDN: 'uid=myadminusername,ou=users,dc=example,dc=org',
  bindCredentials: 'mypassword',
  searchBase: 'ou=users,dc=example,dc=org',
  searchFilter: '(uid={{username}})',
  reconnect: true,
});

var rejectBasicAuth = function (res) {
  res.statusCode = 401;
  res.setHeader('WWW-Authenticate', 'Basic realm="Example"');
  res.end('Access denied');
};

var basicAuthMiddleware = function (req, res, next) {
  var credentials = basicAuth(req);
  if (!credentials) {
    return rejectBasicAuth(res);
  }

  ldap.authenticate(credentials.name, credentials.pass, function (err, user) {
    if (err) {
      return rejectBasicAuth(res);
    }

    req.user = user;
    next();
  });
};

License

MIT

ldapauth-fork has been partially sponsored by Wakeone Ltd.