如何使用电子表格.只读而不是完整的读/写权限范围



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

使用电子表格应用程序服务的文档似乎要求您提供完整的r/w范围只是打开一个工作表;通过ID或URL,即openById()或openByURL()要求:

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

但是我想只使用下面的作用域:

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

我觉得在Apps Script中应该很容易做到这一点,但我在文档中找不到关于它的任何东西。

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

是否有一个"简单"的只读接口谷歌应用程序脚本提供或我需要移植我的项目到一个标准的谷歌云项目,启用表API,找出API密钥,并了解如何应用oauth范围从appsscript清单分开?

问题及解决方法:

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

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

用法:

1。准备一个Google Apps Script项目

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

2。启用表单API。

为了从使用https://www.googleapis.com/auth/spreadsheets.readonly范围的电子表格中检索值,使用了Sheets API。因此,请在高级谷歌服务中启用表单API。Ref

3。准备舱单文件

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

并且,请添加您期望的范围如下。您可以看到,Sheets API已经包含在enabledAdvancedServices中。请按如下方式添加"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);
}
  • About "Method: spreadsheets.get",这是你的问题。

5。测试。

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

注意:

  • https://www.googleapis.com/auth/spreadsheets.readonly的作用域可用于从电子表格中检索值。当您想要更新电子表格时,需要使用https://www.googleapis.com/auth/spreadsheets的范围。请小心。
  • 参考:

  • 方法:spreadsheets.get

相关内容

最新更新