node.js - 从 Nodejs 脚本获取 Microsoft GRAPH 访问 token

标签 node.js azure azure-active-directory microsoft-graph-api

这个问题建立在 How to get Microsoft Graph API Access token from Node Script? 的基础上但是,作为首次用户,我没有必要的声誉来评论该线程中已接受的答案。

问题是,我尝试实现已接受答案建议的方法,但在某个地方出了问题。下面的代码是异步函数的一部分,我已经可以告诉您ONEDRIVE_TENANT_URI的格式为XXX.onmicrosoft.com

const endpoint = `https://login.microsoftonline.com/${process.env.ONEDRIVE_TENTANT_URI}/oauth2/token`;
const requestParams = {
  grant_type: "client_credentials",
  client_id: process.env.ONEDRIVE_APP_ID,
  client_secret: process.env.ONEDRIVE_CLIENT_SECRET,
  resource: "https://graph.windows.net"
};

const authResponse = await request.post({
  url: endpoint,
  form: requestParams
});

authResponse 获取一个字符串作为其正文,其中填写了上面定义的 requestParams。

如果我通过 Postman 提交 post 请求,并使用与 x-www-form-urlencoded 相同的参数,我确实会在响应正文中获得一个 access_token

所以...我做错了什么?也许 - 但我不这么认为 - 这是因为这个函数是由(出于测试目的)带有 json 格式主体的 POSTMAN GET 请求调用的?

最佳答案

您可以下载示例here 。并在 config.js 中填写凭据。您可以从 Azure 门户找到它们。 enter image description here

这是获取访问 token 的代码。

auth.getAccessToken = function () {
  var deferred = Q.defer();

  // These are the parameters necessary for the OAuth 2.0 Client Credentials Grant Flow.
  // For more information, see Service to Service Calls Using Client Credentials (https://msdn.microsoft.com/library/azure/dn645543.aspx).
  var requestParams = {
    grant_type: 'client_credentials',
    client_id: config.clientId,
    client_secret: config.clientSecret,
    resource: 'https://graph.microsoft.com'
  };

  // Make a request to the token issuing endpoint.
  request.post({ url: config.tokenEndpoint, form: requestParams }, function (err, response, body) {
    var parsedBody = JSON.parse(body);
    console.log(parsedBody);
    if (err) {
      deferred.reject(err);
    } else if (parsedBody.error) {
      deferred.reject(parsedBody.error_description);
    } else {
      // If successful, return the access token.
      deferred.resolve(parsedBody.access_token);
    }
  });

  return deferred.promise;
};

您将成功获取访问 token 。 enter image description here

关于node.js - 从 Nodejs 脚本获取 Microsoft GRAPH 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167866/

相关文章:

javascript - 在 Node.js 中调用一组 http.get 请求完成

azure - 如何将 azure 磁盘恢复到以前的快照?

azure - Microsoft Azure DocumentDB 与 Azure 表存储

c# - 通过 OpenID Connect 从 Azure AD 获取用户的电子邮件地址

azure-active-directory - 如何将 ACL 集成到基于 Azure Databricks 的 Azure AD 组

node.js - 如何使用 node.js 将图像文件保存到 sequelize db

javascript - 使用 AJAX 请求抓取页面

c# - 如何在 MVC View 中显示外键值

reactjs - 使用react-aad-msal从react SPA调用web api缺少范围

javascript - Node Express 将变量从客户端传递到服务器