通过服务帐户访问Google Sheets API,该服务帐户通过域范围的委派模拟用户

问题描述

示例代码

from google.oauth2 import service_account 
import pygsheets

creds = service_account.Credentials.from_service_account_file(
    'my/path/to/credentials.json',scopes=('https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive'),subject='account@mydomain.com'
)
pg = pygsheets.authorize(custom_credentials=creds)
pg.open_by_url('https://docs.google.com/spreadsheets/d/my_spreadsheet_id/edit#gid=my_sheet_id')

问题行为

最后一行Client is unauthorized to retrieve access tokens using this method,or client not authorized for any of the scopes requested.失败

预期的行为

最后一行为Google表格访问提供了一个对象。

其他信息

  • 已为服务帐户启用域范围的委派,subject帐户位于域上
  • 工作表已与subject帐户共享
  • 当我不提供subject并直接与服务帐户共享工作表时,它会起作用

环境

  • python==3.6.9
  • pygsheets==2.0.3.1
  • google-auth==1.6.3

解决方法

使用域范围委派时要考虑的问题

默认情况下,不启用域范围的委派。要允许它,您需要按照documentation中所述的步骤进行操作。

  1. 步骤:在GCP控制台中:
  • 您需要为要用于此目的的每个服务帐户激活复选框Enable G Suite Domain-wide Delegation 要使用服务帐户模拟用户,您需要在管理控制台中授予必要的权限
  1. 在管理控制台中:
  • 模拟用户时服务帐户所需的任何范围都必须在管理控制台中授权
  • 为此请转到Main menu menu> Security > API controls.
  • 通过其Client ID添加(如果尚未完成)感兴趣的服务帐户,为其提供所需的所有范围并进行授权
  • 如果需要,您可以在以后随时修改范围

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...