【发布时间】: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 的文档。没有带有密钥
body的option。 -
祝福你@TheMaster。只需将其更改为“有效负载”,它就像一个魅力。
-
很高兴知道。问题是问题,答案是答案。不要改变问题来回答。
标签: api google-apps-script oauth-2.0 office365 access-token