谷歌云如何在应用程序代码中认证用户而不是服务帐户?

2024-04-29 09:03:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件用户身份验证json应用程序角色选项帐户
1条回答
网友
1楼 · 发布于 2024-04-29 09:03:39

经过一些挖掘,部分归功于@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类的实例时,一个浏览器会启动,并要求用户登录到google并确认应用程序的权限,然后返回第二组凭据,然后用于实例化应用程序使用的Secretmanager客户端

相关问题 更多 >