如何用NodeJS从Active Directory获取countryCode属性?
Retrieving Additional User Attributes (countryCode, company, employeeID) with activedirectory
It looks like you’re on the right track with the activedirectory package, but by default, the findUsers method only fetches a limited set of user attributes. To get the specific details you need—like countryCode, company, and employeeID—you’ll need to explicitly specify these fields in your query options.
Here’s how to modify your code to include those attributes:
var ActiveDirectory = require('activedirectory'); var ad = new ActiveDirectory({ url: 'ldap://mydomain.com', baseDN: 'dc=mydomain, dc=com', username: 'sample@mydomain.com', password: 'sample' }); // List the exact attributes you want to retrieve var desiredAttributes = ['cn', 'countryCode', 'company', 'employeeID', 'givenName', 'sn']; var query = 'cn=jem'; // Pass the attributes option to findUsers ad.findUsers(query, { attributes: desiredAttributes }, function(err, users) { if (err) { console.log('ERROR: ' + JSON.stringify(err)); return; } if (!users || users.length === 0) { console.log('No users found matching the query.'); return; } // Log the full user details with your target attributes users.forEach(user => { console.log('User Details:'); console.log(`CN: ${user.cn}`); console.log(`Country Code: ${user.countryCode}`); console.log(`Company: ${user.company}`); console.log(`Employee ID: ${user.employeeID}`); console.log('---'); }); });
Key Tips:
- Explicit Attribute Selection: The
attributesoption lets you pick exactly which fields to pull from Active Directory. Don’t forget to include any default attributes you still need (likecnfor your query match). - Schema Check: Make sure these attributes exist in your AD schema and are populated for the users you’re querying. Some attributes might be optional or unused in your domain.
- Result Handling: I added a check for empty results to avoid errors if no users match your query.
If you ever need every available attribute for a user (not recommended for performance unless necessary), you can use attributes: ['*'] instead of listing individual fields.
内容的提问来源于stack exchange,提问作者Anand Rajagopal
相关产品推荐
相关产品推荐

