1

Cannot grant access to Common Data Service with NodeJS

I am implementing a simple Node function which will get some data from Common Data Service. I can get the accessToken already, but when I use this accessToken to access Common Data Service, the response is ‘Unauthorized’.

I followed the instruction here ( https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/walkthrough-registering-configuring-simplespa-application-adal-js ) and is able to get it worked with simple page app.

I just want to port it to Node and have the app grant access to Common Data Service without requiring a user to login.

const fetch = require('node-fetch');
const AuthenticationContext = require('adal-node').AuthenticationContext;

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const resource = "https://my-org.crm5.dynamics.com";
    const clientId = 'my client id';
    const clientSecret = 'my client secret';
    const authorityHostUrl = 'https://login.microsoftonline.com';
    const tenant = 'my-tenant-name.onmicrosoft.com'; // AAD Tenant name.
    const authorityUrl = authorityHostUrl + '/' + tenant;

    const authContext = new AuthenticationContext(authorityUrl);

    const tokenResp = await new Promise((resolve, reject) => {
        authContext.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function (err, tokenResponse) {
            if (err) {
                context.error("cannot get token: " + err.stack);
                return reject(err.stack);
            } else {
                return resolve(tokenResponse);
            }
        });
    });

    context.log("tokenResp: ", tokenResp); // The tokenResp contains accessToken

    const cdsHeaders = {};
    cdsHeaders["Authorization"] = "Bearer " + tokenResp.accessToken;
    cdsHeaders["Accept"] = "application/json";
    cdsHeaders["Content-Type"] = "application/json; charset=utf-8";
    cdsHeaders["OData-MaxVersion"] = "4.0";
    cdsHeaders["OData-Version"] = "4.0";

    const endpointUrl = encodeURI(resource + "/api/data/v9.0/accounts?$select=name,address1_city&$top=10");
    const dataResponse = await fetch(endpointUrl, { method: 'GET', headers: cdsHeaders });

    console.log("response: ", dataResponse); // The dataResponse is 401 Unauthorized

    context.res = { body: "Done" };
};
Felix
  • 63
  • 6

1 Answers1

1

I got the solution: I have to 'Manually create a CDS for Apps application user' in order for it to work, regarding this document: https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/authenticate-oauth#connect-as-an-app

Although the sample code is in C#, there are not too many differences between C# and Node.js clients.

Felix
  • 63
  • 6