如何将 Active Directory 令牌 curl 命令转换为节点获取

How to convert Active Directory Token curl command to a node-fetch

当我将自己的租户 ID、客户端 ID 和客户端密码放入以下位置时成功运行的 CURL 命令:

# 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'

我使用 node-fetch 的尝试出错了:

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

我收到的错误:

  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'

我的 node-fetch POST 请求中的正文有什么问题?

顺便说一下,我已经尝试过使用 Axios 并得到了相同的结果。

AD 正在等待表单请求,试试这个

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/x-www-form-urlencoded'},
        body: '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)
      })