1

无法使用 NodeJS 授予对 Common Data Service 的访问权限

我正在实现一个简单的节点函数,它将从 Common Data Service 获取一些数据。我已经可以获取 accessToken,但是当我使用此 accessToken 访问 Common Data Service 时,响应是“未授权”。

我按照这里的说明(https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/walkthrough-registering-configuring-simplespa-application-adal-js)并能够得到它使用简单的页面应用程序。

我只想将它移植到 Node 并让应用程序授予对 Common Data Service 的访问权限,而无需用户登录。

const fetch = require('node-fetch');
const AuthenticationContext = require('adal-node').AuthenticationContext;

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const resource = "https://my-org.crm5.dynamics.com";
    const clientId = 'my client id';
    const clientSecret = 'my client secret';
    const authorityHostUrl = 'https://login.microsoftonline.com';
    const tenant = 'my-tenant-name.onmicrosoft.com'; // AAD Tenant name.
    const authorityUrl = authorityHostUrl + '/' + tenant;

    const authContext = new AuthenticationContext(authorityUrl);

    const tokenResp = await new Promise((resolve, reject) => {
        authContext.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function (err, tokenResponse) {
            if (err) {
                context.error("cannot get token: " + err.stack);
                return reject(err.stack);
            } else {
                return resolve(tokenResponse);
            }
        });
    });

    context.log("tokenResp: ", tokenResp); // The tokenResp contains accessToken

    const cdsHeaders = {};
    cdsHeaders["Authorization"] = "Bearer " + tokenResp.accessToken;
    cdsHeaders["Accept"] = "application/json";
    cdsHeaders["Content-Type"] = "application/json; charset=utf-8";
    cdsHeaders["OData-MaxVersion"] = "4.0";
    cdsHeaders["OData-Version"] = "4.0";

    const endpointUrl = encodeURI(resource + "/api/data/v9.0/accounts?$select=name,address1_city&$top=10");
    const dataResponse = await fetch(endpointUrl, { method: 'GET', headers: cdsHeaders });

    console.log("response: ", dataResponse); // The dataResponse is 401 Unauthorized

    context.res = { body: "Done" };
};
4

1 回答 1

1

我得到了解决方案:关于此文档,我必须“为应用程序用户手动创建 CDS”才能正常工作:https ://docs.microsoft.com/en-us/powerapps/developer/common-data -service/authenticate-oauth#connect-as-an-app

虽然示例代码是用 C# 编写的,但 C# 和 Node.js 客户端之间并没有太多区别。

于 2019-01-29T09:38:14.113 回答