【问题标题】:How to use spreadsheets.readonly instead of the full read/write auth scope如何使用 spreadsheets.readonly 而不是完整的读/写授权范围
【发布时间】:2022-11-23 09:15:31
【问题描述】:

我正在使用谷歌应用程序脚本为我的组织创建一个网络应用程序。该应用程序的功能归结为从不同的工作表读取数据并将其显示给用户。

使用 SpreadsheetApp 服务的文档似乎要求您提供完整的 r/w 范围只是为了打开一个工作表;通过 ID 或 URL 即 openById() 或 openByURL() 需要:

    https://www.googleapis.com/auth/spreadsheets

但是我只想使用以下范围。

    https://www.googleapis.com/auth/spreadsheets.readonly

我觉得在 Apps 脚本中应该很容易做到这一点,但我在文档中找不到任何相关内容。

我找到了一些与我想要的相关的东西here。然而,这似乎非常复杂,需要管理 API 密钥。

是否有 Google Apps 脚本提供的“简单”只读界面,或者我是否需要将我的项目移植到标准的谷歌云项目,启用 Sheets API,找出 API 密钥,并了解如何应用 oauth 范围与应用程序清单?

【问题讨论】:

  • 虽然我不确定我提出的答案是否符合您的预期a 'simple' read-only interface Google Apps Script provides,但我提出了一个答案。你能确认一下吗?如果那没有用,我深表歉意。

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


【解决方案1】:

问题和解决方法:

不幸的是,在现阶段,当使用电子表格服务(SpreadsheetApp)时,需要使用https://www.googleapis.com/auth/spreadsheets的范围。这似乎是当前的规范。比如之前使用DriveApp时,需要使用https://www.googleapis.com/auth/drive的范围。但是,通过谷歌方面的更新,当使用DriveApp.getFiles()时,可以使用https://www.googleapis.com/auth/drive.readonly。所以,我认为电子表格服务的情况可能会在未来的更新中改变。

但是,在当前阶段,需要使用当前规范。因此,需要使用变通方法。在这个答案中,我想提出一个使用范围为 https://www.googleapis.com/auth/spreadsheets.readonly 的电子表格的解决方法。

用法:

1. 准备一个 Google Apps 脚本项目。

请创建一个新的 Google Apps 脚本项目。在这种情况下,您可以同时使用独立类型和容器绑定脚本类型。在这个答案中,我想使用独立类型。如果想直接创建,请访问https://script.new。由此,您可以看到 Google Apps Script 的脚本编辑器。请设置文件名。

2. 启用表格 API。

为了使用https://www.googleapis.com/auth/spreadsheets.readonly 的范围从 Spreadsheet 中检索值,使用了 Sheets API。因此,请在 Advanced Google 服务中启用 Sheets API。 Ref

3.准备清单文件。

在使用脚本之前,请设置清单文件(appsscript.json)。所以,请出示清单文件。 Ref

并且,请按如下方式添加您的预期范围。可以看到enabledAdvancedServices中已经包含了Sheets API。请按以下方式添加"oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.readonly"]

{
  "timeZone": "###",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Sheets",
        "version": "v4",
        "serviceId": "sheets"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.readonly"]
}

4.准备示例脚本。

请将以下脚本复制并粘贴到您的脚本编辑器中,并设置spreadsheetId,然后保存脚本。

function myFunction() {
  const spreadsheetId = "###"; // Please set your Spreadsheet ID.

  const res = Sheets.Spreadsheets.get(spreadsheetId);
  console.log(res);
}
  • 关于“方法:电子表格.get”,这是您的问题。

5. 测试。

当您运行myFunction 时,脚本就会运行。并且,返回电子表格的值。这样,您就可以使用范围为https://www.googleapis.com/auth/spreadsheets.readonly 的 Sheets API 从 Spreadsheet 中检索值。

笔记:

  • https://www.googleapis.com/auth/spreadsheets.readonly 的范围可用于从电子表格中检索值。当您要更新电子表格时,需要使用https://www.googleapis.com/auth/spreadsheets 的范围。请注意这一点。

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多