如何使用 nodejs 和 node-fetch 从 Azure 为 Microsoft Graph 获取客户端令牌

How to get a client token from Azure for Microsoft Graph using nodejs and node-fetch

我一直在尝试遵循方向 here 并将其应用于 nodejs。

我收到以下错误:

  error: 'invalid_request',
  error_description: "AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\n" +
    'Trace ID: <trace id>\r\n' +
    'Correlation ID: <correlation id>\r\n' +
    'Timestamp: 2021-05-12 22:27:30Z',
  error_codes: [ 900144 ],
  timestamp: '2021-05-12 22:27:30Z',
  trace_id: '<trace id>',
  correlation_id: '<correlation id>',
  error_uri: 'https://login.microsoftonline.com/error?code=900144'

这是我的代码。

const fetch = require('node-fetch');
let  tenantId='<my tenant id>';


    let token = fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
        method: 'post',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            client_id: '<my client id>',
            scope: 'https://graph.microsoft.com',
            client_secret: '<my client secret>',
            grant_type: 'client_credentials',
        })
      }).then(function(response) {
        return response.json()
      }).then(json => {
          console.log(json)
      })

为什么我的 body 没有看到 'grant_type'?

问这个问题的另一种方法可能是,如何使用 POST:

将此 curl 命令转换为 node-fetch 请求
# Replace {tenant} with your tenant!
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id=535fb089-9ff3-47b6-9bfb-4f1264799865&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=qWgdYAmab0YSkuL1qKv5bPX&grant_type=client_credentials' 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'

我应该注意到,当我传递我的租户 ID、客户端 ID 和机密时,这个 CURL 示例确实可以正常工作。

我的fetchbody怎么了?

试试这个:

const fetch = require('node-fetch');

let  tenantId='';
let  clientID = '';
let clientSecret = '';

let token = fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
    method: 'post',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: `client_id=${clientID}&Client_secret=${clientSecret}&grant_type=client_credentials&scope=https://graph.microsoft.com/.default`
    }).then(function(response) {
    return response.json()
    }).then(json => {
        console.log(json)
    })

结果: