【问题标题】:Unable to generate OAuth 2.0 Access Token from Office365 via JavaScript无法通过 JavaScript 从 Office365 生成 OAuth 2.0 访问令牌
【发布时间】:2020-08-18 03:05:09
【问题描述】:

我正在尝试通过 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'

我已经用谷歌搜索过这个错误并找到了一堆不同的解决方案,并尝试实施它们但无济于事。我想这与 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 Fetch 代码之间唯一真正的区别是:

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

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

【问题讨论】:

  • 阅读 urlfetch 的文档。没有带有密钥bodyoption
  • 祝福你@TheMaster。只需将其更改为“有效负载”,它就像一个魅力。
  • 很高兴知道。问题是问题,答案是答案。不要改变问题来回答。

标签: api google-apps-script oauth-2.0 office365 access-token


【解决方案1】:

这已通过根据 documentation 将 UrlFetchApp 的“正文”更改为“有效负载”来解决。编辑代码以反映更改。感谢 @TheMaster 指出我的错误。

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

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2018-02-19
    • 2013-02-23
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多