Hello Guys!
I have a usecase to call CRM APIs from my Nodejs client with non-interactive login. For this I have a client key and secret generated after registering my App on Azure Active Directory. I am successful in generating access token, but anytime I attempt to access data (via a Microsoft OData client or straight Web API HTTP requests), I always receive a 401, despite the inclusion of my access token in the authorization header. Here is my Nodejs client:
var adal = require('adal-node');
var azure = require('azure');
var express = require('express');
var https = require('https');
var app = express();
var AuthenticationContext = adal.AuthenticationContext;
var authorityHostUrl = 'login.microsoftonline.com';
var tenant = 'xxxx.onmicrosoft.com';
var authorityUrl = authorityHostUrl + '/' + tenant;
var clientId = 'xxxx';
var clientSecret = 'xxxx'
var resource = 'https://xxxx.crm.dynamics.com';
var context = new AuthenticationContext(authorityUrl);
var accessToken;
var credentials;
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
if (err) {
console.log('well that didn\'t work: ' + err.stack);
} else {
console.log("======================SUCCESS=======================");
accessToken=tokenResponse.accessToken;
console.log(accessToken);
}
});
app.get('/accounts', function(req, res) {
var token = "Bearer " + accessToken;
console.log(token);
var options = {
host: 'xxxx.crm.dynamics.com',
path: '/api/data/v8.2/accounts?$select=name,address1_city&$top=10',
headers: {
'Authorization': token,
'Accept': 'application/json',
'Content-Type':'application/json; charset=utf-8',
'OData-MaxVersion':'4.0',
'OData-Version':'4.0'
}
};
callback = function(response) {
console.log("Callback Invoked");
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
console.log("Data ====>"+str);
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log("Complete Data ====>"+str);
console.log(str);
});
}
console.log(options);
https.request(options, callback).end();
});
app.listen(3000);
*This post is locked for comments