使用工作负载联合身份验证在 Python 中验证 Google-Cloud-Storage

Zaf*_*fer 5 python google-cloud-storage google-cloud-platform openid-connect

是否可以使用 Google 工作负载联合身份验证的 OIDC 方法来验证我的 Python 应用程序的 Google Cloud Storage 包。

我想做这样的事情:

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)
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误:

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.

Daz*_*kin 3

查看Sal 的Exchange Generic OIDC Credentials for GCP Credentials存储库上的Automatic

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

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

请参阅google.auth,具体而言(在 之后export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json)您可以:

import google.auth

credentials, project_id = google.auth.default()
Run Code Online (Sandbox Code Playgroud)