使用 Google Compute Engine 上的应用程序默认凭据访问 Sheets API

Jan*_*auw 7 python google-authentication google-compute-engine google-cloud-platform google-sheets-api

ADC(应用程序默认凭据)工作流程是否仅支持 Google Cloud API(例如,支持 Google Cloud Storage API,但不支持 Google Sheet API)?

我指的是google.auth 的默认方法- 不必在代码中存储任何私钥是一个巨大的胜利,也是有效利用 ADC(应用程序默认凭据)设置的主要好处。

GOOGLE_APPLICATION_CREDENTIALS如果我将环境变量设置为私钥文件(例如 key.json),则以下代码将有效。default这与包中步骤 1 的方法一致google.auth1. If the environment variable GOOGLE_APPLICATION_CREDENTIALS is set to the path of a valid service account JSON private key file, then it is loaded and returned.

import google.auth
from apiclient import discovery

credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])

sheets = discovery.build('sheets', 'v4', credentials=credentials)

SPREADSHEETID = '....'

result = sheets.spreadsheets().values().get(spreadsheetId=SPREADSHEETID, range='Sheet1!A:B').execute()

print result.get('values', [])
Run Code Online (Sandbox Code Playgroud)

现在,看看该方法的第 4 步:4. If the application is running in Compute Engine or the App Engine flexible environment then the credentials and project ID are obtained from the Metadata Service.

如果我删除GOOGLE_APPLICATION_CREDENTIALSGoogle Compute 实例上的环境变量,则会收到以下错误:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/..../values/Sheet1%21A%3AB?alt=json returned "Request had insufficient authentication scopes.">

这与 Cloud Console 中的 Google 向导不一致: 找出您需要什么凭证

您不需要任何凭据

F10*_*F10 2

根据此文档,您使用的范围需要Oauth 2.0授权。因此,需要用户登录并同意。