Browse project docs

Authentication and Bind Example

Validate LDAP credentials with a complete ldapjs-community bind example and reliable connection cleanup.

On this page

LDAP simple bind verifies a distinguished name and password. Use an encrypted connection before sending credentials outside a trusted local test environment.

Link to EnvironmentEnvironment

bash
export LDAP_URL='ldaps://directory.example.com:636'
export LDAP_USER_DN='uid=ada,ou=people,dc=example,dc=com'
export LDAP_USER_PASSWORD='replace-me'
export LDAP_CA_FILE='/path/to/directory-ca.pem'

Link to CodeCode

javascript
const fs = require('node:fs')
const ldap = require('ldapjs')

const required = ['LDAP_URL', 'LDAP_USER_DN', 'LDAP_USER_PASSWORD', 'LDAP_CA_FILE']
for (const name of required) {
  if (!process.env[name]) throw new Error(`Missing ${name}`)
}

const client = ldap.createClient({
  url: process.env.LDAP_URL,
  connectTimeout: 5000,
  tlsOptions: {
    ca: [fs.readFileSync(process.env.LDAP_CA_FILE)]
  }
})

let finished = false
function close(exitCode) {
  if (finished) return
  finished = true
  client.unbind(() => {
    process.exitCode = exitCode
  })
}

client.on('error', (err) => {
  console.error('LDAP connection error:', err.message)
  close(1)
})

client.bind(process.env.LDAP_USER_DN, process.env.LDAP_USER_PASSWORD, (err) => {
  if (err) {
    console.error('Authentication failed:', err.message)
    close(1)
    return
  }

  console.log('Authentication succeeded')
  close(0)
})

Run it with node authenticate.js. A successful bind proves the supplied credentials were accepted for that connection; it does not by itself determine application authorization.