javascriptnode.jsldapldapjs

Retrieving User Information from LDAP Active Directory Server with Node.js using ldapjs package


I'm trying to create a function that fetches all details for a user from the Active Directory using ldapjs in Node.js. Here is the function I'm using:


const ldapConfig = {
    url: 'ldap://your-ldap-server',
    bindDN: 'cn=admin,dc=example,dc=com',
    bindCredentials: 'admin-password',
    searchBase: 'dc=example,dc=com',
    searchOptions: {
        scope: 'sub',
        attributes: ['*'] // Fetch all attributes
    }
};

function searchLDAPByUserPrincipalName(userPrincipalName, callback) {
    const client = ldap.createClient({
        url: ldapConfig.url
    });

    console.log('Connecting to LDAP server...');

    client.bind(ldapConfig.bindDN, ldapConfig.bindCredentials, (err) => {
        if (err) {
            console.error('Bind error:', err);
            return callback(err);
        }

        console.log('Bind successful');

        const opts = {
            ...ldapConfig.searchOptions,
            filter: `(&(objectClass=person)(userPrincipalName=${userPrincipalName}))`
        };

        client.search(ldapConfig.searchBase, opts, (err, res) => {
            if (err) {
                console.error('Search error:', err);
                client.unbind();
                return callback(err);
            }

            let user = null;

            res.on('searchEntry', (entry) => {
                console.log('Entry found:', JSON.stringify(entry.object, null, 2));
                user = entry.object;
            });

            res.on('searchReference', (referral) => {
                console.log('Referral:', referral.uris.join());
            });

            res.on('error', (err) => {
                console.error('Search entry error:', err);
                client.unbind();
                return callback(err);
            });

            res.on('end', (result) => {
                console.log('Search end status:', result.status);
                client.unbind();
                if (result.status !== 0) {
                    return callback(new Error(`Non-zero status from LDAP search: ${result.status}`));
                }
                callback(null, user);
            });
        });
    });
}

// Example usage
searchLDAPByUserPrincipalName('jdoe@example.com', (err, user) => {
    if (err) {
        console.error('LDAP search failed:', err);
    } else {
        console.log('User found:', user);
    }
});```

When I run this code, I expect to see the user details in the log. However, I'm getting the following log output:

my-form\src> node server.js
Connecting to LDAP server...
Bind successful
Entry found: undefined
Search end status: 0
User found: undefined

I can see that the LDAP connection and binding are successful, and the search options look correct. However, the Entry found and User found logs show undefined.

What I have tried so far:

Double-checked the ldapConfig values to ensure they are correct. Verified that the userPrincipalName being searched exists in the directory. Logged the search options to confirm they include the correct filter and attributes. Despite these steps, the user information is still not being fetched. Can anyone help me understand why the user is coming back as undefined and how to fix it?


Solution

  • I solved my issue with this:

        let parsed = {};
        if (entry.object) {
            parsed = entry.object;
        } else if (entry.attributes) {
            entry.attributes.forEach(attr => {
                parsed[attr.type] = attr.vals;
            });
        }
        return parsed;
    }