通过全域委派模拟用户的服务帐户访问 Google 工作表 API 失败
Accessing Google Sheets API through a service account impersonating a user through domain-wide delegation fails
示例代码
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 Sheet 的访问提供了一个对象。
附加信息
- 已为服务帐户启用全域委派,
subject
帐户在域中
- Sheet 与
subject
帐户共享
- 当我不提供
subject
并直接与服务帐户共享 sheet 时,它有效
环境
python==3.6.9
pygsheets==2.0.3.1
google-auth==1.6.3
使用domain-wide授权时要考虑
默认情况下不启用 domain-wide 委派。要允许它,您需要按照 documentation.
中描述的步骤进行操作
- 步骤:在 GCP 控制台中:
- 您需要为要用于此目的的每个服务帐户激活复选框
Enable G Suite Domain-wide Delegation
要使用服务帐户模拟用户,您需要在管理控制台中授予必要的权限
- 在管理控制台中:
- 服务帐户在模拟用户时所需的任何范围都必须在管理控制台中获得授权
- 为此转到
Main menu menu> Security > API controls.
- 通过
Client ID
添加(如果尚未完成)感兴趣的服务帐户,为其提供所需的所有范围并授权
- 如果需要,您可以在以后随时修改范围
示例代码
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 Sheet 的访问提供了一个对象。
附加信息
- 已为服务帐户启用全域委派,
subject
帐户在域中 - Sheet 与
subject
帐户共享 - 当我不提供
subject
并直接与服务帐户共享 sheet 时,它有效
环境
python==3.6.9
pygsheets==2.0.3.1
google-auth==1.6.3
使用domain-wide授权时要考虑
默认情况下不启用 domain-wide 委派。要允许它,您需要按照 documentation.
中描述的步骤进行操作- 步骤:在 GCP 控制台中:
- 您需要为要用于此目的的每个服务帐户激活复选框
Enable G Suite Domain-wide Delegation
要使用服务帐户模拟用户,您需要在管理控制台中授予必要的权限
- 在管理控制台中:
- 服务帐户在模拟用户时所需的任何范围都必须在管理控制台中获得授权
- 为此转到
Main menu menu> Security > API controls.
- 通过
Client ID
添加(如果尚未完成)感兴趣的服务帐户,为其提供所需的所有范围并授权 - 如果需要,您可以在以后随时修改范围