In my current project, we had a need to build a Node JS app that will authenticate with an App Registration client id and client secret. First thing that came into my mind was to use msal library. But I hit a snag due to CORS issue and there was very little I could do with the code as it was a boiler plate code and changes were limited.

So, I went to the basics of Web Api call from JavaScript to authenticate with App Registration. For this I use the request object and the code is as below.

const getAuthToken = async function() {
    let config = require(__dirname + "/../config/config.json");
    var request = require('request');
    var options = {
        'method': 'POST',
        'url': 'https://login.microsoftonline.com/3bd27ef8-8d38-4656-86d2-5f0d90a73981/oauth2/token',
        'headers': {
            'Authorization': 'Basic ' + new Buffer(config.clientId + ":" + config.clientSecret).toString('base64'),
            'Content-Type': 'application/x-www-form-encoded'
        },
        form: {
            'grant_type': 'client_credentials',
            'resource': 'https://analysis.windows.net/powerbi/api'
        }
    };

    return new Promise(
        (resolve, reject) => {
            request(options, function (error, response) {
                if (error) {
                    reject(error);
                }
                resolve(JSON.parse(response.body));
            });
        }
    );
}

module.exports.getAuthenticationToken = getAuthToken;

You will notice that the config entries are defined in config.json file. Then we define request object and configure the options object. In this options object we define the method, url and headers needed along with the form. Because this is an authentication request, we need to supply the following headers:

Authorization which will be basic authentication with username and password encoded in base64.

Content-Type will be application/x-www-form-encoded

We also need to pass the body as a form; as highlighted in the code. If you are going to use the token retrieved for some other request then need to pass the request domain in the resource. Under form you should also specify grant_type as client_credentials.

This module returns a Promise object by parsing the response body; as highlighted on the code.

Hope this helps.

For more content subscribe to my blogs and follow me on:

Don’t forget to subscribe to my Power Platform ProDev Newsletter

1 comment

Leave a comment