Monday, 17 April 2017

Usage of adal-node to get an AccessToken from a node js script

I have a Node JS Script that has as input parameters the Client ID and Secret. Once I read them in my script, I would like to get an accessToken that I will use to generate an HTTP request to call an API. All within my NodeJS script.

I've seen there is an adal-node module that should help me with it but I haven't figure out how to actually get the accessToken.

I've seen there are two main functions, acquireTokenWithAuthorizationCode and adquireTokenWithClientCredentials

I tried with the adquireTokenWithClientCredentials option with below code but the AccessToken it returns is wrong since it gives a 401 response (Unauthorized: Access is denied due to invalid credentials)

function getAccessToken(clientId, clientSecret, resource){
    return new Promise(function(resolve, reject){
        var authorityHostUrl = <HOST_URL>;
        var tenant = '<TENANT>.onmicrosoft.com';
        var authorityUrl = authorityHostUrl + '/' + tenant;

        var context = new adal(authorityUrl);
        context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse){
            if (err) {
                reject(err);
            } else {
                resolve(tokenResponse.accessToken);
            } 
        });
    });
};

With that being said, I believe that I need to use the acquireTokenWithAuthorizationCode method but I don't really know how to create a simple function thas has the Client ID and Secret as parameters and return a string with the accessToken. Something similar to what I did above. In this case, I need a req.query.code and redirectUri that I don't know where to get from. Also, I don't understand the callback in this case.

Could someone point me to some code that does something like that?



via user3587624

No comments:

Post a Comment