web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

News and Announcements icon
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Azure token not working in Dynamics 365

(0) ShareShare
ReportReport
Posted on by

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&amp;$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();
}

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hey PhillySerge,

    What I noticed is you are using the Azure identifier as your 'resource'.

    To get a valid access token for the Dynamics 365 (CRM) api, you need to pass the organization API url as 'resource'.
    In your example that would be "https://<MyCompany>.api.crm.dynamics.com"

    var resource = 'https://<MyCompany>.api.crm.dynamics.com';

    Also, where you are opening your XMLHttpRequest, I noticed you didn't include "https://", which is also required.

    Hope this helps you out. If you have any questions, let me know and if you found my answer helpful, please mark it as such :-)

  • Community Member Profile Picture
    on at

    Thank you Michel!  

    I just copied the resource wrong from one om my trial js, it was correct in real code.  

    It was the "https://".  It's always the small oversights.  I now can get in, but not getting any results, but that could be a permissions issue in the role i assigned the application user.  Thanks again and let me see if I can figure out why I'm getting a NULL result back.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Season of Sharing Community Challenge Launch!

Jump in, show your community spirit, and win prizes!

Women in Power Builds Momentum

Expanding mentorship, skilling, and AI innovation

Congratulations to the May Top 10 Community Leaders

These are the community rock stars!

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
ScottDurow Profile Picture

ScottDurow 2

#2
GJones Profile Picture

GJones 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans