Google Sheet API 使用应用程序默认凭据访问

Google Sheet API access with Application Default credentials

我正在尝试从 Python(在 GKE 中运行)访问 Google Sheet(只读模式)。

我能够获得应用程序默认凭据,但出现范围问题(因为我缺少 https://www.googleapis.com/auth/spreadsheets.readonly 范围)。请参阅下面的代码:

from googleapiclient.discovery import build
from oauth2client import client

creds=client.GoogleCredentials.get_application_default()
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
sheet.values().get(spreadsheetId='XXXXXXXXXX', range='Sheet1!A:C').execute()

输出为:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/XXXXXX/values/Sheet1%21A%3AC?alt=json returned "Request had insufficient authentication scopes.">

我试图阅读任何可用的文档,但所有相关范围都在使用外部服务帐户 JSON 文件。

有没有办法使用 Application Default 并添加所需的范围?

答案:

您需要在 GoogleCredentials.get_application_default()create_scoped() 方法中定义范围。

代码片段:

creds = GoogleCredentials.get_application_default().create_scoped(
          ['https://www.googleapis.com/auth/spreadsheets.readonly'])

参考文献:

oauth2client 现已弃用。请改用此库 google-auth
用户指南在这里:
https://google-auth.readthedocs.io/en/master/user-guide.html

所以这段代码:

from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build

scopes = [
    'https://www.googleapis.com/auth/cloud-platform'
    'https://www.googleapis.com/auth/spreadsheets.readonly',
]
credentials = GoogleCredentials.get_application_default().create_scoped(scopes)
service = build('sheets', 'v4', credentials=credentials)

应替换为此代码:

from google import auth
from googleapiclient.discovery import build

scopes = [
    'https://www.googleapis.com/auth/cloud-platform'
    'https://www.googleapis.com/auth/spreadsheets.readonly',
]
credentials, project_id = auth.default(scopes=scopes)  # Returns a tuple.
service = build('sheets', 'v4', credentials=credentials)

此外,根据此回复,库 google-auth 可能需要另一个库 google-auth-httplib2 才能正常工作:
https://github.com/googleapis/google-auth-library-python/issues/190#issuecomment-322837328