【问题标题】:Authenticate to Gsuite APIs without service account在没有服务帐户的情况下向 Gsuite API 进行身份验证
【发布时间】:2020-04-16 11:27:50
【问题描述】:

我正在尝试使用我的本地凭据(即不是服务帐户)读取 Google 电子表格。我基本上在做:

from googleapiclient.discovery import build

service = build('sheets', 'v4')
request = sheet_service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range='{}!A1:a4'.format(SHEET_NAME))
result = request.execute()
values = result.get('values', [])

但是我得到以下错误:

Traceback (most recent call last):
  File "./update_incidents_tracker.py", line 54, in <module>
    sys.exit(main())
  File "./update_incidents_tracker.py", line 48, in main
    result = request.execute()
  File "/home/filip/.virtualenvs/monitoring-tools/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/filip/.virtualenvs/monitoring-tools/lib/python3.6/site-packages/googleapiclient/http.py", line 898, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/1lTcQ3WknG_2oZvy9O9LEbgAzoykOWaheYSaDkkV21wE/values/Incidents%21A1%3Aa4?alt=json returned "Request had insufficient authentication scopes.">

我找不到为我的本地 (gcloud SDK) 凭据设置范围的方法。如何设置合适的范围?

作为基于服务帐户的身份验证的参考,我可以简单地运行:

credentials = service_account.Credentials.from_service_account_file(CREDENTIALS_FILE, scopes=SCOPES)
build('sheets', 'v4', credentials=credentials)

【问题讨论】:

  • 如果您已经下载了凭证文件,您可以关注this quickstart
  • 我不想使用服务帐户,因为我正在编写一个脚本,多个用户将在他们的机器上运行。我不希望所有这些都经过 SA 代,这很麻烦。
  • 我提供的快速入门不涉及服务帐户。每个用户都将使用自己的凭据。

标签: google-sheets google-cloud-platform google-oauth gcloud google-workspace


【解决方案1】:

显式使用默认凭据,此时设置范围

import google.auth

credentials, project_id = google.auth.default(scopes=....)
build('sheets', 'v4', credentials=credentials)
....

google-auth here的完整文档

【讨论】:

  • 我仍然收到有关范围不足的错误。阅读代码后,如果默认凭据来自 gcloud SDK,则似乎未应用范围。还是我做错了什么?
  • 您的代码在哪里运行?您当前的默认凭据是什么?
  • 您使用什么范围?应该是one of these
  • 我使用googleapis.com/auth/spreadsheets,并在我的笔记本电脑上运行它。如果我调用 google.auth.default,它会使用我的 gcloud SDK 凭据。
  • 您只能在 API 密钥上生成身份令牌。生成服务帐户 qui 文件,执行 gcloud auth activate-service-account --key-file=key.json 其中 key.json 是您的服务帐户密钥文件,然后重试。
猜你喜欢
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多