使用 Google Compute Engine 上的应用默认凭据访问 Sheets API [英] Use Application Default Credentials on Google Compute Engine to access Sheets API

本文介绍了使用 Google Compute Engine 上的应用默认凭据访问 Sheets API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我指的是

解决方案

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

Does the ADC (Application Default Credentials) workflow only support Google Cloud APIs (for example, supports for Google Cloud Storage API, but not the Google Sheet API)?

I'm referring to google.auth's default method - not having to store any private keys with the code is a great win and the main benefit of making effective use of the ADC (Application Default Credentials) setup.

The following code works if I set the GOOGLE_APPLICATION_CREDENTIALS environmental variable to the private key file, say key.json. This is inline with the default method as per step 1 of the google.auth package: 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', [])

Now, looking at step 4 of the method: 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.

If i remove the GOOGLE_APPLICATION_CREDENTIALS environmental variable on a Google Compute instance, I get the following error:

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.">

This is not consistent with Google's wizard as per the Cloud Console:

解决方案

According to this documentation, the scope that you're using requires Oauth 2.0 authorization. Therefore, a user login and consent is required.

这篇关于使用 Google Compute Engine 上的应用默认凭据访问 Sheets API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆