Make authentication with an LDAP server easy.
This library use ldapts as the underneath library. It has three modes of authentications:
-
Admin authenticate mode. If an admin user is provided, the library will login (ldap bind) with the admin user, then search for the user to be authenticated, get its DN (distinguish name), then use the user DN and password to login again. If every thing is ok, the user details will be returned.
-
Self authenticate mode. If the admin user is not provided, then the
userDnanduserPasswordmust be provided. If any ofuserSearchBaseorusernameAttributeis missing, then the lib simply does a login with theuserDnanduserPassword(ldap bind), and returns true if succeeds.Otherwise, the lib does a login with the
userDnanduserPassword(ldap bind), then does a search on the user and return the user's details. -
Verify user exists. If an
verifyUserExists : trueis provided, the library will login (ldap bind) with the admin user, then search for the user to be verified. If the user exists, user details will be returned (without verifying the user's password).
In addition, the fetchUsers() function can be used to fetch all users under a search base, using the admin
account to search (without any username or password of the individual users). The search always uses
LDAP paged results, so the common server-side limit of 1000 entries per search does not apply.
- Can use an admin to search and authenticate a user
- Can also use a regular user and authenticate the user itself
- Supports ldap, ldaps, and STARTTLS
- Async/Await Promise
npm install ldap-authentication --save-
An example on how to use with Passport is passport-ldap-example
-
Another simple library express-passport-ldap-mongoose provide turn key solution
let authenticated = await authenticate({
ldapOpts: { url: 'ldap://ldap.forumsys.com' },
userDn: 'uid=gauss,dc=example,dc=com',
userPassword: 'password',
})let authenticated = await authenticate({
ldapOpts: { url: 'ldap://ldap.forumsys.com' },
userDn: 'uid=gauss,dc=example,dc=com',
userPassword: 'password',
userSearchBase: 'dc=example,dc=com',
usernameAttribute: 'uid',
username: 'gauss',
attributes: ['dn', 'sn', 'cn'],
})let authenticated = await authenticate({
ldapOpts: { url: 'ldap://ldap.forumsys.com' },
userDn: 'uid=gauss,dc=example,dc=com',
verifyUserExists: true,
userSearchBase: 'dc=example,dc=com',
usernameAttribute: 'uid',
username: 'gauss',
})let authenticated = await authenticate({
ldapOpts: { url: 'ldap://ldap.forumsys.com' },
userDn: 'uid=gauss,dc=example,dc=com',
userPassword: 'password',
userSearchBase: 'dc=example,dc=com',
usernameAttribute: 'uid',
username: 'gauss',
groupsSearchBase: 'dc=example,dc=com',
groupClass: 'groupOfUniqueNames',
groupMemberAttribute: 'uniqueMember',
// groupMemberUserAttribute: 'dn'
})const { fetchUsers } = require('ldap-authentication')
let users = await fetchUsers({
ldapOpts: { url: 'ldap://ldap.forumsys.com' },
adminDn: 'cn=read-only-admin,dc=example,dc=com',
adminPassword: 'password',
userSearchBase: 'dc=example,dc=com',
// userFilter: '(objectClass=person)', // default: (|(uid=*)(sAMAccountName=*))
// attributes: ['uid', 'sn', 'mail'], // omitted = all attributes
// pageSize: 500, // default: 1000
})The library works with both CommonJS and ES modules:
import { authenticate } from 'ldap-authentication'
// or
const { authenticate } = require('ldap-authentication')const { authenticate } = require('ldap-authentication')
async function auth() {
// auth with admin
let options = {
ldapOpts: {
url: 'ldap://ldap.forumsys.com',
// tlsOptions: { rejectUnauthorized: false }
},
adminDn: 'cn=read-only-admin,dc=example,dc=com',
adminPassword: 'password',
userPassword: 'password',
userSearchBase: 'dc=example,dc=com',
usernameAttribute: 'uid',
username: 'gauss',
// starttls: false
}
let user = await authenticate(options)
console.log(user)
// auth with regular user
options = {
ldapOpts: {
url: 'ldap://ldap.forumsys.com',
// tlsOptions: { rejectUnauthorized: false }
},
userDn: 'uid=einstein,dc=example,dc=com',
userPassword: 'password',
userSearchBase: 'dc=example,dc=com',
usernameAttribute: 'uid',
username: 'einstein',
// starttls: false
}
user = await authenticate(options)
console.log(user)
}
auth()import { authenticate } from 'ldap-authentication'
async function auth() {
// auth with admin
let options = {
ldapOpts: {
url: 'ldap://ldap.example.com',
tlsOptions: {
rejectUnauthorized: false, // For self-signed certificates
minVersion: 'TLSv1.2',
servername: 'ldap.example.com' // For SNI (Server Name Indication)
}
},
starttls: true, // Enable StartTLS
adminDn: 'cn=admin,dc=example,dc=com',
adminPassword: 'password',
userPassword: 'password',
userSearchBase: 'dc=example,dc=com',
usernameAttribute: 'uid',
username: 'testuser'
}
let user = await authenticate(options)
console.log(user)
}
auth()Important Notes for StartTLS:
- Use
ldap://URLs withstarttls: true(notldaps://) - For
ldaps://URLs, omitstarttlsand the connection will use TLS from the start - TLS options like
rejectUnauthorized,minVersion, andservernamecan be specified inldapOpts.tlsOptions
The example/ directory contains complete, runnable scripts: admin auth, self auth, group lookup,
fetchUsers, verifyUserExists, and StartTLS. They run against the bundled seeded test server
(start it via docker compose up -d, or point LDAP_URL at your own server):
docker compose up -d # seeded OpenLDAP on localhost:1389 / 1636
node example/fetch-users.mjs # or any other script in example/
docker compose downldapOpts: This is passed toldaptsclient directlyurl: url of the ldap server. Example:ldap://ldap.forumsys.comtlsOptions: options to pass to node tls. Example:{ rejectUnauthorized: false }connectTimeout: Int. Default:5000. Connect timeout in ms
adminDn: The DN of the admistrator. Example:cn=read-only-admin,dc=example,dc=com,adminPassword: The password of the admin.userDn: The DN of the user to be authenticated. This is only needed ifadminDnandadminPasswordare not provided. Example:uid=gauss,dc=example,dc=comuserPassword: The password of the userverifyUserExists: iftrueuser existence will be verified without passworduserSearchBase: The ldap base DN to search the user. Example:dc=example,dc=comusernameAttribute: The ldap search equality attribute name corresponding to the user's username. It will be used with the value inusernameto construct an ldap filter as({attribute}={username})to find the user and get user details in LDAP. In self authenticate mode (userDnanduserPasswordare provided, but notadminDnandadminPassword), if this value is not set, then authenticate will return true right after user bind succeed. No user details from LDAP search will be performed and returned. Example:uidusernameFilter: Prioritized alternative to usernameAttribute, allows you to provide a filter where{{username}}will be replaced with the username provided Example:(|(uid={{username}})(mail={{username}}))username: The username to authenticate with. It is used together with the name inusernameAttributeto construct an ldap filter as({attribute}={username})to find the user and get user details in LDAP. Example:some user inputuserFilter: (used byfetchUsers()) The ldap search filter to select the users to return. By default it is(|(uid=*)(sAMAccountName=*)), which matches both POSIX (uid) and Active Directory (sAMAccountName) users. Example:'(objectClass=person)', or'(objectClass=*)'to match everythingpageSize: (used byfetchUsers()) The number of entries to fetch per page for the paged search. Default:1000attributes: A list of attributes of a user details to be returned from the LDAP server. If is set to[]or ommited, all details will be returned. Example:['sn', 'cn']starttls: Boolean. UseSTARTTLSor not. Whentrue, the connection will be upgraded to TLS using the STARTTLS extended operation. TLS options can be specified inldapOpts.tlsOptions. Note: Usestarttls: truewithldap://URLs, notldaps://URLsgroupsSearchBase: if specified with groupClass, will serve as search base for authenticated user groupsgroupClass: if specified with groupsSearchBase, will be used as objectClass in search filter for authenticated user groupsgroupMemberAttribute: if specified with groupClass and groupsSearchBase, will be used as member name (if not specified this defaults tomember) in search filter for authenticated user groupsgroupMemberUserAttribute: if specified with groupClass and groupsSearchBase, will be used as the attribute on the user object (if not specified this defaults todn) in search filter for authenticated user groups
| Mode (call) | Required | Commonly used in addition |
|---|---|---|
Admin authenticate (authenticate) |
ldapOpts, adminDn, adminPassword, userPassword, userSearchBase, usernameAttribute or usernameFilter, username |
attributes, groupsSearchBase, groupClass, starttls |
Self authenticate (authenticate) |
ldapOpts, userDn, userPassword |
userSearchBase, usernameAttribute, attributes, groupsSearchBase, starttls |
Verify user exists (authenticate with verifyUserExists: true) |
ldapOpts, adminDn, adminPassword, userSearchBase, usernameAttribute or usernameFilter, username |
attributes, groupsSearchBase, starttls |
Fetch all users (fetchUsers) |
ldapOpts, adminDn, adminPassword, userSearchBase |
userFilter, attributes, pageSize, starttls |
The user object if authenticate() is success.
In version 4, a new function is added: authenticateResult(). It has the same call signature as authenticate() but returns an object AuthenticationResult with more details.
authenticate() and fetchUsers() throw a LdapAuthenticationError on failure:
authenticate(): when the failure corresponds to a known outcome, the error'scodeproperty holds the matching AUTH_RESULT_* constant (the same valueauthenticateResult()reports).- Missing required options throw a
LdapAuthenticationErrortoo, with all missing fields listed in the message in a single error.
fetchUsers() returns an array of user objects, one per matched LDAP entry (each with its dn and the returned attributes), or an empty array if no user matches the filter.
AuthenticationResult object has the following fields:
code: number. constants:AUTH_RESULT_FAILURE= 0AUTH_RESULT_SUCCESS= 1AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND= -1AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS= -2AUTH_RESULT_FAILURE_CREDENTIAL_INVALID= -3AUTH_RESULT_FAILURE_UNCATEGORIZED= -4
identity: identity supplied as stringuser: user object if authentication is successful, otherwise nullmessage: authentication message array, which contains server messagesclient: ldapClient instance
- A typical admin bind DN is a service or admin account, e.g.
cn=Administrator,cn=users,dc=example,dc=com, or a dedicated LDAP sync account. - Username attributes:
sAMAccountNamefor logins likejdoe,userPrincipalNameforjdoe@example.com. To look a user up by either at once, useusernameFilter: '(|(sAMAccountName={{username}})(userPrincipalName={{username}}))'. - Set
userSearchBaseto the OU containing the users (e.g.ou=users,dc=example,dc=com): the search is faster and avoidsAUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS. fetchUsers()uses LDAP paged results, so Active Directory's usual 1000-entry limit per search is not an issue (adjust the page size withpageSizeif needed).- Binary attributes such as
thumbnailPhotoshould be requested asthumbnailPhoto;binary; they are returned as base64-encoded strings.
| Symptom | Likely cause / fix |
|---|---|
ECONNREFUSED, ETIMEDOUT, or other connect errors |
ldapOpts.url is wrong or the server is unreachable. Check the URL, the network/firewall, and connectTimeout. |
LdapAuthenticationError with admin bind failed / user bind failed |
Wrong adminDn/adminPassword, or userDn/userPassword in self mode. Verify the bind manually, e.g. ldapsearch -b dc=example,dc=com -D <dn> -w <password> dn. |
identity not found (AUTH_RESULT_FAILURE_IDENTITY_NOT_FOUND) |
The user does not exist under userSearchBase, or usernameAttribute/username/usernameFilter does not match the attribute(s) stored on the server. |
identity ambiguous (AUTH_RESULT_FAILURE_IDENTITY_AMBIGUOUS) |
The search matched multiple entries - narrow userSearchBase or make the filter more specific. |
Invalid credentials (AUTH_RESULT_FAILURE_CREDENTIAL_INVALID) |
The user was found but the password is wrong. |
| TLS certificate errors | For self-signed certificates use tlsOptions: { rejectUnauthorized: false }; add servername for SNI. Use ldaps:// (without starttls) or ldap:// with starttls: true. |
In version 2, The user object has a raw field that has the raw data from the LDAP/AD server. It can be used to access buffer objects (profile pics for example).
Buffer data can now be accessed by user.raw.profilePhoto, etc, instead of user.profilePhoto.
In version 3, the raw field is no longer used. Instead, append ;binary to the attributes you
want to get back as base64-encoded string. Check the following example on how to get a user's profile photo:
export async function verifyLogin(email: string, password: string) {
const options = {
//...other config options
userPassword: password,
username: email,
attributes: ['thumbnailPhoto;binary', 'givenName', 'sn', 'sAMAccountName', 'userPrincipalName', 'memberOf' ]
};
try {
const ldapUser = await authenticate(options);
if (!ldapUser) {
return { error: "user not found" };
}
// accessing the image
const profilePhoto = ldapUser['thumbnailPhoto;binary'];
/* using the image
<img src={`data:image/*;base64,${profilePhoto}`} />
*/
return { user: ldapUser };
}
}Version 2 supports Node version 12, 14, 15, 16, 17 and 18.
Version 3 supports Node version 16, 17, 18, 20 and 22.
Version 4 supports Node version 22 and above.