【发布时间】:2020-08-24 10:27:46
【问题描述】:
我在网上找到了从 Google Drive 获取文件元数据的代码摘录。我将它添加到 Google 表格中的自定义菜单中,但它从脚本编辑器和表格中返回 403。它作为未经验证的应用程序第一次要求授权,以后再也没有。
我试图弄清楚,但我对授权部分完全感到困惑。代码检索并发送一个 Authorization 标头,但令牌在 Sheets 中来自哪里?它不应该在谷歌服务之间自动创建吗?以及如何指定 Drive 需要的范围?我找不到任何用于授权的表格脚本示例,只有 NodeJS 等客户端。
我无意中在脚本编辑器中找到了高级 Google 服务菜单,并同时启用了表格和云端硬盘 API。没有相关的自定义 GCP 项目(此脚本有一个 Apps 脚本管理的 Cloud Platform 项目)。
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('First item', 'menuItem1')
.addToUi();
}
function menuItem1() {
getFileMetaData("1GrX86wNWbEBf3Or90bXCyd31w-yVINiM"); // hardcoded for now
}
function getFileMetaData(fileID) {
var api = "https://www.googleapis.com/drive/v2/files/" + fileID;
var params = {
method:"get",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var json = UrlFetchApp.fetch(api, params).getContentText();
var meta = JSON.parse(json);
Logger.log(json);
SpreadsheetApp.getUi().alert(json);
}
结果:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission: Request had insufficient authentication scopes."
}
],
"code": 403,
"message": "Insufficient Permission: Request had insufficient authentication scopes."
}
}
如果我删除授权标头:
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
【问题讨论】:
-
为什么不使用 UrlFetch 而不是 Advanced Service?这样,您就不需要指定所需的范围。此外,您可以在清单文件中明确设置所需的范围,请查看this。
标签: google-apps-script google-sheets google-drive-api