【问题标题】:Generate Google API access_token in Google Colab from Python在 Google Colab 中从 Python 生成 Google API access_token
【发布时间】:2020-06-01 16:52:06
【问题描述】:

我需要从 Google Colab 中的 Python 生成具有某些特定范围 ['https://www.googleapis.com/auth/bigquery', 'https://www.googleapis.com/auth/cloud-platform']access_token

默认情况下,Google Colab 在colabtools 内部提供了一个函数来验证用户身份。

from google.colab import auth
auth.authenticate_user()
print('Authenticated')

但是生成的凭证文件包含一个固定范围的列表,不包括我需要的。

import os
with open(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) as f:
  print(f.read())
...
"scopes": [
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/appengine.admin",
    "https://www.googleapis.com/auth/accounts.reauth",
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/compute",
    "https://www.googleapis.com/auth/userinfo.email"
  ],
...

我尝试使用google.auth.Credentials 类和google.oauth2.Credentials 类使用google-authenter code here 生成有效的凭据令牌。我可以生成类的有效实例,但是当我检查令牌时为无。

有没有办法使用 Python 的自定义范围为 Google API 生成有效的access_token

谢谢!

【问题讨论】:

    标签: oauth-2.0 google-api access-token google-colaboratory google-api-python-client


    【解决方案1】:

    如果您将虚拟机与 Google Colab 一起使用,则可以使用以下命令(示例)在该虚拟机上设置服务帐户的范围:

    gcloud compute instances set-service-account example-instance \
       --service-account my-sa-123@my-project-123.iam.gserviceaccount.com \
       --scopes compute-rw,storage-ro
    

    然后,在 Python 中进行身份验证时,生成的凭据将包含正确的范围。

    【讨论】:

      猜你喜欢
      • 2022-11-18
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2020-04-16
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多