通过云功能访问 Google 工作表 Python API 的身份验证问题

Authentication issue accessing Google Sheets Python API via cloud functions

我正在尝试使用云函数访问 Google sheet 和 python 中的 sheets API,但获得 403 权限错误。我已经创建了一个服务帐户,导出了密钥(包含在我正在上传的云函数 zip 中)并为该服务帐户提供了访问 sheets 所需的 API 范围(我已经尝试了 https://www.googleapis.com/auth/spreadsheets and https://www.googleapis.com/auth/drive).这是代码:

import httplib2
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def main(request):
  scope = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']

  credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scope)

  service = build('sheets', 'v4', http=credentials.authorize(httplib2.Http()))

  spreadsheet_id = 'id-of-the-google-sheet'

  range = 'Sheet1!A:D'

  response = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range).execute()

  cols = response.get('values', [])[0]
  return cols[0]

requirements.txt:

google-api-python-client
oauth2client
google-auth-httplib2
google-auth

如果我明确与服务帐户共享 Google sheet,则身份验证有效,我可以访问 sheet 数据。问题是为什么这不能通过应用适当的 API 范围作为 Google 帐户管理员来工作?

Google 驱动器权限在范围之上。请求的身份验证需要范围,但驱动器权限(以及 Sheets 的扩展)决定了谁有权访问哪个文件。 如果呼叫帐户(在本例中为服务帐户)无法访问有问题的 Sheet,您将收到您一直收到的 403。

在管理控制台中设置范围与权限没有直接关联。

还有一点需要注意,如果默认情况下您将文档共享给 G Suite 帐户中的所有人,您可以使用域范围委派 (1) 并使用 serviceaccount 在G 套件域。您不需要与服务帐户本身共享每个文档。

(1) This one is for the Admin SDK,但这是包含最佳示例的文章。您对那里的凭据对象感兴趣。您还可以使用 .json IIRC.

创建对象