All,
I'm been (unsuccessfully) trying to create a Web Service Integration piece to sync data between non MS servers and CRM using Javascript. This is a service that should run x times per day without user intervention (no manual log in). I registered the user and application in Azure AD, created the App User in CRM, changed the App manifest in Azure.
Using the ADAL library and using the following code: context.acquireTokenWithClientCredentials(resource, applicationId, clientSecret, function(err, tokenResponse) I am sucessful in aquiring the token but when I pass it in a JQuery or XMLHttpRequest I get a 401 Error "Unauthorized". Even if I copy the token directly into Lattimer's CRM REST Builder tool I get the same result. Any ideas?
Here's the simplified code:
'use strict';
var https = require('https');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var authorityHostUrl = 'https://login.windows.net';
var tenant = '<MyCompany>.onmicrosoft.com'; // Azure AD Tenant.
var authorityUrl = authorityHostUrl + '/' + tenant;
var applicationId = 'XXXX-XXX-XXX-XXXX'; // App Id of app registered under Azure.
var clientSecret = 'XXXX-XXX-XXX-XXXX'; // Secret generated for app.
var resource = 'https://<MyCompany>.onmicrosoft.com/XXXX-XXX-XXX-XXXX';
var context = new AuthenticationContext(authorityUrl);
context.acquireTokenWithClientCredentials(resource, applicationId, clientSecret, function(err, tokenResponse) {
if (err) {
console.log('Problem, didn\'t work: ' + err.stack);
} else {
var tempToken = JSON.stringify(tokenResponse);
var newtempToken = JSON.parse(tempToken.toString());
var token = newtempToken.accessToken;
//console.log(token);
getContacts(token);
}
});
function getContacts(token){
console.log("Heres the token being used " + token); //GOT TOKEN
var req = new XMLHttpRequest();
req.open("GET", "<MyCompany>.api.crm.dynamics.com/api/data/v8.2/contacts?$select=ContactId,FullName&$top=1", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=7");
req.setRequestHeader("Authorization", "Bearer " + token);
//req.setRequestHeader("MSCRMCallerID", ""); //Tried impersonation also
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var contactid = results.value[i]["contactid"];
var fullname = results.value[i]["fullname"];
}
} else {
console.error(this.statusText);
}
}
};
req.send();
}