【问题标题】:How to convert Active Directory Token curl command to a node-fetch如何将 Active Directory 令牌 curl 命令转换为节点获取
【发布时间】:2021-08-03 08:07:15
【问题描述】:

当我将自己的租户 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,也得到了相同的结果。

【问题讨论】:

  • curl 使用的是 url 编码格式。为什么在转换中使用 JSON?
  • 我也尝试过使用 url-encoded,但我得到了同样的错误。
  • 这是您在curl 命令中的真实客户端 ID 和客户端密码吗?
  • 不,这是来自 Microsoft 的文档:github.com/MicrosoftDocs/azure-docs/blob/master/articles/…
  • 澄清一下,当您使用 url 编码时,您只是将工作 curl 命令中的相同内容作为字符串放入,对吧?

标签: javascript azure curl azure-active-directory node-fetch


【解决方案1】:

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

【讨论】:

  • 我尝试了application/x-www-form-urlencoded,但收到了同样的错误。
  • @Dshiz 抱歉,我按下了保存按钮来快速 :) 更新了我的答案。 SO body 应该是一个字符串
  • 好的..让我试试这个
  • 等一下.. 我忘了换成'application/x-www-form-urlencoded'。我现在遇到了一个新错误……那很好!
  • 是的,我想是的。在处理新问题时,我将接受这个答案...感谢您的帮助!
猜你喜欢
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 2021-10-08
  • 2021-03-28
  • 1970-01-01
  • 2017-07-12
相关资源
最近更新 更多