首页 > 解决方案 > Google Cloud - 如何在应用代码中验证用户而不是服务帐户?

问题描述

我可以通过在 GC 控制台中创建和下载 credentials.json 来授权服务帐户。但此选项不适用于实际的人类用户帐户。我的用户帐户具有某些我想在应用程序中使用的角色,并且需要以该用户帐户身份进行身份验证。我该怎么办?有没有办法为用户帐户下载类似的 creds.json 文件?

标签: pythongoogle-cloud-platformoauth-2.0google-authentication

解决方案


经过一番挖掘并部分感谢@JohnHanley,我设法使用 google-cloud oauth 库代表具有正确权限的人类用户来验证我的应用程序:

from google.cloud import secretmanager_v1beta1 as secretmanager
from google_auth_oauthlib import flow

SecretManagerAdminCreds = 'credentials.json'
LAUNCH_BROWSER = True


class SecretManagerAdmin:
    def __init__(self, project_id: str = "gcp_project_id",
                 scopes: list = ['https://www.googleapis.com/auth/cloud-platform']):
        self._scopes = scopes
        self._project_id = project_id

        appflow = flow.InstalledAppFlow.from_client_secrets_file(SecretManagerAdminCreds, scopes=self._scopes)

        if LAUNCH_BROWSER:
            appflow.run_local_server()
        else:
            appflow.run_console()

        authed_creds = appflow.credentials

        self.client = secretmanager.SecretManagerServiceClient(credentials=authed_creds)

当我创建我的 SecretManagerAdmin 类的实例时,浏览器会启动并要求用户登录谷歌并确认应用程序的权限,并返回第二组凭据,然后用于实例化应用程序使用的 Secretmanager 客户端.


推荐阅读