无法通过 JavaScript 从 Office365 生成 OAuth 2.0 访问令牌

Unable to generate OAuth 2.0 Access Token from Office365 via JavaScript

我正在尝试通过 OAuth 2.0 client credentials grant flow 从 Office365 的 /token 身份平台端点提取访问令牌。我已经注册了我的应用程序、客户端 ID 和密码等...

我可以在 Postman 中发出 POST 请求并毫无问题地接收访问令牌:

但是,当我通过 JavaScript(通过 Google Apps 脚本)尝试 POST 请求时,我收到一条错误消息:AADSTS900144: The request body must contain the following parameter: 'grant_type'

我已经 Google 遇到过这个错误,并找到了很多不同的解决方案,并尝试实施它们但无济于事。我想这与 URL 编码有关,但无法弄清楚。

代码:

function getO365() {
  // POST Request (To get Access Token)
  var tenantID = 'longstringhere'
  var appID = 'longstringhere'
  var appSecret = 'longstringhere'
  var graphScore = 'https://graph.microsoft.com/.default'

  var url = 'https://login.microsoftonline.com/' + tenantID + '/oauth2/v2.0/token'

  var data = {
    'client_id': appID,
    'scope': graphScore,
    'client_secret': appSecret,
    'grant_type': 'client_credentials'
  };

  var postOptions = {
    'method': 'POST',
    'headers': {
      'Accept': 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    'body': data,
    'redirect': 'follow'
  };

  var authToken = UrlFetchApp.fetch(url, postOptions);

}

我的代码与我从 Postman 提取的 JavaScript 获取代码之间唯一真正的区别是:

var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "longstringhere");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "longstringhere");
urlencoded.append("grant_type", "client_credentials");

当我尝试在 Google Apps 脚本中使用 URLSearchParams 时,我不断收到此错误:ReferenceError: URLSearchParams is not defined

有什么想法吗?提前致谢!

根据 documentation. Edited code to reflect the change. Credit to @TheMaster 指出我的错误,将 UrlFetchApp 的 'body' 更改为 'payload' 解决了这个问题。

'payload': data,//from   'body': data,