Server-to-server authentication and API connectivity with Microsoft Dynamics 365 CRM

I have the ability to call the CRM API from my Nodejs client with non-interactive login. To do this, I have a client key and a secret generated after registering my application in Azure Active Directory. I will be able to create an access token, but at any time I try to access the data (through the Microsoft OData client or direct HTTP HTTP requests), I always get 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 = 'https://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); 
+5
source share

Source: https://habr.com/ru/post/1266844/


All Articles