繁体   English   中英

使用 Workload Identity Federation 对 Python 中的 Google-Cloud-Storage 进行身份验证

[英]Authenticate Google-Cloud-Storage in Python using Workload Identity Federation

是否可以使用 Google Workload Identity Federation 的 OIDC 方法对我的 Python 应用程序的 Google Cloud Storage package 进行身份验证。

我想做这样的事情:

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = str(os.path.dirname(os.path.dirname(__file__))) + "/keys/credentials.json"
from google.cloud import storage

import google.oauth2.id_token
import google.auth.transport.requests

request = google.auth.transport.requests.Request()
target_audience = "https://pubsub.googleapis.com"

obtained_id_token = google.oauth2.id_token.fetch_id_token(request, target_audience)

storage_client = storage.Client(credentials=obtained_id_token)

这给出了以下错误:

ValueError: This library only supports credentials from google-auth-library-python. See https://google-auth.readthedocs.io/en/latest/ for help on authentication with this library.

查看自动在 Sal 的Exchange Generic OIDC Credentials for GCP Credentials repo 上。

IIUC 这将您从联合凭据获取到 Google 应用程序默认凭据(见下文),您可以将其与任何Google SDK 一起使用。

对于@john-hanley 的评论,您错误地使用了 auth 库。

请参阅google.auth ,特别是(在export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json ),您可以:

import google.auth

credentials, project_id = google.auth.default()

不能直接回复评论但是

作为参考,这里有一些描述更多的链接

  • federation 会将您的环境aws|oidc|azure凭据交换为 GCP 理解的凭据(不涉及 svc 帐户密钥),请参阅gcp 工作负载身份联合

  • google 发布的 oidc ( id_tokens ) 通常在这里用于访问您在云运行上部署的服务等,请参见google id tokens

  • 最后,只是为了参考,谷歌有非常具体的方式使用 svc 帐户 jwt (它不是 oidc 也不是 oauth 而是谷歌特定的东西)对某些服务进行身份验证......它一点也不常见,但它在此处描述,请参见ZCFD61B8A7397FA7C10B2AE58FBAFABAE

这并不能解决问题的 Workload Identity Federation 部分,但确实使问题代码正常工作:

import google.oauth2.id_token
import google.auth.transport.requests

request = google.auth.transport.requests.Request()
target_audience = "https://storage.cloud.google.com/"

# Create ID token credentials.
credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request)

# Refresh the credential to obtain an ID token.
credentials.refresh(request)

id_token = credentials.token
id_token_expiry = credentials.expiry

storage_client = storage.Client(credentials=credentials)
bucket = storage_client.get_bucket(settings.GOOGLE_CLOUD_BUCKET_NAME)

仍然需要查看是否可以在不需要 repo 中的 Credentials json 文件的情况下进行身份验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM