【问题标题】:Access Google Drive from Sheets: authorization从表格访问 Google 云端硬盘:授权
【发布时间】: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


【解决方案1】:

...如何指定 Drive 需要的范围?

您需要在代码中的某处调用DriveApp。只需将其放入 cmets 即可。我用过

// DriveApp.getStorageLimit();

过去当我想通过UrlFetchApp 使用 API 时触发云端硬盘授权。

您可以通过打开文件 > 项目属性中的对话框来检查在线编辑器中已授权的范围。单击 Scopes 选项卡以查看脚本当前授权状态的列表。

编辑:

另一种选择是在清单文件上设置授权范围:Setting explicit scopes

此外,如果您使用 Advanced Service 而不是调用 UrlFetchApp,则无需担心指定正确的范围。

【讨论】:

  • 我永远不会猜到这个解决方案。对于初学者来说,这是一个非常恶劣的环境。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2012-07-12
  • 1970-01-01
  • 2017-07-12
  • 1970-01-01
相关资源
最近更新 更多