服务器到服务器身份验证以及与Microsoft Dynamics 365 CRM的API通信

时间:2017-04-18 09:45:58

标签: azure dynamics-crm-2011 dynamics-crm microsoft-dynamics

我有一个用于通过非交互式登录从我的Nodejs客户端调用CRM API的用例。为此,我在Azure Active Directory上注册我的应用程序后生成了客户端密钥和密钥。我成功生成访问令牌,但无论何时我尝试访问数据(通过Microsoft OData客户端或直接Web API HTTP请求),我总是会收到401,尽管在授权标头中包含了我的访问令牌。这是我的Nodejs客户端:

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);

0 个答案:

没有答案