Search code examples
node.jsazureactive-directoryazure-active-directoryldapjs

How to connect and find a user from Azure AD using Nodejs


I am trying to find a user from the azure active directory using nodejs. I am using Node-ActiveDirectory for this task. First I tried to connect to the Azure active directory as the given example in the above link. example code as below that I have used.

var ActiveDirectory = require('activedirectory');
var config = { url: 'ldap://myhotmail.onmicrosoft.com',
    baseDN: 'dc=myhotmail,dc=onmicrosoft,dc=com',
    username: 'roledene@myhotmail.onmicrosoft.com',
    password: 'myPassword'
}
var ad = new ActiveDirectory(config);

var username = 'roledene@myhotmail.onmicrosoft.com';
var password = 'myPassword';

ad.authenticate(username, password, function(err, auth) {
    if (err) {
        console.log('ERROR: '+JSON.stringify(err));
        return;
    }

    if (auth) {
        console.log('Authenticated!');
    }
    else {
        console.log('Authentication failed!');
    }
});

but it gives the following error. what is wrong with this code ?

ERROR: {"code":"ENOTFOUND","errno":"ENOTFOUND","syscall":"getaddrinfo","hostname":"myhotmail.onmicrosoft.com","host":"myhotmail.onmicrosoft.com","port":389}

Solution

  • as @juunas comment, I tried with the Microsoft Graph client.

    I will quote the initial step for setup the ms graph client which is exactly mentioned in here for more details

    Installing ms graph client

    npm install @microsoft/microsoft-graph-client
    

    connect and query from MS graph api

    const MicrosoftGraph = require("@microsoft/microsoft-graph-client");
    
    var client = MicrosoftGraph.Client.init({
        authProvider: (iss, sub, profile, accessToken, refreshToken, done) => {
            done(null, {
                profile,
                accessToken,
                refreshToken
            }); //first parameter takes an error if you can't get an access token
        }
    });
    
    // Example calling /me with no parameters
    client
        .api('/me')
        .get((err, res) => {
            console.log(res); // prints info about authenticated user
        });