【问题标题】:Authentication issue accessing Google Sheets Python API via cloud functions通过云函数访问 Google Sheets Python API 的身份验证问题
【发布时间】:2018-11-02 18:45:03
【问题描述】:

我正在尝试使用云函数和 python 中的工作表 API 访问 Google 工作表,但出现 403 权限错误。我创建了一个服务帐户,导出了密钥(包含在我正在上传的云功能 zip 中),并为该服务帐户提供了访问工作表所需的 API 范围(我尝试了 https://www.googleapis.com/auth/spreadsheetshttps://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 表格,则身份验证确实有效,并且我可以访问表格数据。问题是为什么这不能通过作为 Google 帐户管理员应用适当的 API 范围来工作?

【问题讨论】:

标签: python google-cloud-functions google-sheets-api google-oauth google-api-python-client


【解决方案1】:

Google 云端硬盘权限位于范围之上。请求的身份验证需要范围,但驱动器权限(以及扩展名的表格)决定了谁可以访问哪个文件。 如果调用帐户(在本例中为服务帐户)无权访问相关工作表,您将获得您所获得的 403。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多