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

时间:2018-08-16 23:22:12

标签: python google-cloud-platform google-compute-engine google-sheets-api google-authentication

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

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

如果我将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为私钥文件(例如key.json),则以下代码有效。这符合default程序包第1步中的google.auth方法:1. 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', [])

现在,请看方法的第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 Compute实例上删除了GOOGLE_APPLICATION_CREDENTIALS环境变量,则会出现以下错误:

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的向导不一致: find out what credentials you need

you don't need any credentials

2 个答案:

答案 0 :(得分:3)

凭据对于构建构造函数是可选的。省略它们,然后将使用Cloud Function服务帐户对工作表进行身份验证。

from apiclient import discovery

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

SPREADSHEETID = '....'

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

print result.get('values', [])

答案 1 :(得分:1)

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