从表格访问Google云端硬盘:授权

时间:2020-08-24 10:27:46

标签: google-apps-script google-sheets google-drive-api

我在网上找到了一段代码摘录,该摘录从Google云端硬盘获取文件元数据。我将其添加到Google表格中的自定义菜单,但它从脚本编辑器和表格中都返回403。它第一次作为未经验证的应用程序要求授权,再也没有。

我试图弄清楚,但对于授权部分我完全感到困惑。该代码检索并发送一个Authorization标头,但是令牌在Sheets中来自哪里?是否应该在Google服务之间自动创建?以及如何指定云端硬盘需要的范围?我找不到任何进行授权的Sheets脚本的示例,仅能找到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."
 }
}

1 个答案:

答案 0 :(得分:3)

...如何指定云端硬盘需要的作用域?

您需要在代码中的某个地方调用DriveApp。只需将其放入评论即可。我用过

// DriveApp.getStorageLimit();
过去

我想通过UrlFetchApp使用API​​时触发Drive授权。

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

编辑:

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

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