google-apps-script - 调用我自己的 Google Apps 脚本时得到 401 响应
问题描述
我使用应用程序脚本编写了一个测试网络应用程序。我将其部署为以“用户访问网络应用程序”的身份执行,并将访问权限设置为“拥有 Google 帐户的任何人”。然后我尝试从另一个充当客户端的脚本调用 Web 应用程序函数。我在登录我的谷歌帐户时完成了所有这些操作,网络应用程序和客户端都在同一个浏览器窗口中(在不同的选项卡中)。但我总是收到 401 错误。然后我尝试将一些 oauthScopes 添加到客户端脚本的 appsscript.json 文件中,但这没有帮助。任何解决此问题的帮助将不胜感激。
网络应用代码:
function doPost(e) {
if(typeof e !== 'undefined') {
let par = e.parameter;
let retval = par.x*3;
let retobj = {"retval":retval};
return ContentService.createTextOutput(JSON.stringify(retobj));
}
}
客户端代码:
function callWebApp(x) {
Logger.log("starting call webapp");
var payload = {
"info" : "some text",
"x" : 3,
"type" : "post",
};
var options = {
"method" : "POST",
"payload" : payload,
"followRedirects" : true,
"muteHttpExceptions": true
};
var result = UrlFetchApp.fetch(urlString, options);
Logger.log(result.getResponseCode());
if (result.getResponseCode() == 200) {
Logger.log('got response');
var params = JSON.parse(result.getContentText());
Logger.log(params.retval);
}
return 1;
}
客户端的 appscript.json:
{
"timeZone": "America/New_York",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"https://www.googleapis.com/auth/script.deployments",
"https://www.googleapis.com/auth/script.deployments.readonly",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/script.processes",
"https://www.googleapis.com/auth/script.projects.readonly"
]
}
执行日志:7:47:30 PM Notice Execution started 7:47:30 PM 信息开始调用 webapp 7:47:30 PM Info 401.0 7:47:30 PM 通知执行完成
解决方案
修改点:
- 当您将 Web 应用程序部署为
Execute as: User accessing the web app
并且Who has access: Anyone with Google account
您希望使用脚本(在本例中为 Google Apps 脚本)访问 Web 应用程序时,需要通过在请求标头中包含访问令牌来请求 Web 应用程序. - 并且,当访问令牌用于向 Web 应用程序请求时,请在您的客户端中包含您当前的范围
https://www.googleapis.com/auth/drive.readonly
和/或范围。https://www.googleapis.com/auth/drive
- 在您的脚本中,似乎
urlString
没有声明。虽然我不确定这是否可能在其他地方声明,但请再次确认。
当这些点反映到你的脚本中时,它变成如下。
修改后的脚本:
从:var options = {
"method" : "POST",
"payload" : payload,
"followRedirects" : true,
"muteHttpExceptions": true
};
至:
var options = {
"method": "POST",
"payload": payload,
"muteHttpExceptions": true,
"headers": {authorization: "Bearer " + ScriptApp.getOAuthToken()}
};
笔记:
- 如果您想使用脚本让用户请求您的 Web 应用程序,还需要通过在请求标头中包含访问令牌来请求 Web 应用程序。此外,还需要与用户共享 Google Apps 脚本项目。请注意这一点。
- 如果在运行上述脚本时无法检索到预期结果,请将 Web 应用程序重新部署为新版本并再次测试。
参考:
推荐阅读
- python - Python 多处理调用类函数
- java - 在构建 gradle 时找不到插件
- python - 根据其他列突出显示 pandas 数据框中的特定列
- python - 用另一列中的值替换特定单词
- input - 如何使 AEM/CRX 中的输入字段成为必需?
- git - 为什么我们第一次使用 git remote add origin?
- javascript - React 添加延迟以在状态中应用类
- android - 无法转换工件 com.twilio:video-android
- arrays - 如何在打字稿的对象数组中找到具有相同属性值的对象?
- python - C++ - 如何将大数组作为函数的输入