GCP-以用户身份模拟服务帐户

问题描述 投票:0回答:1

我想允许用户模仿服务帐户来对长期运行的进程进行操作。但是,所有代码示例都说明了一个模拟另一个服务帐户的服务帐户。

用户可以直接模拟服务帐户吗?如果是这样,如何?

我正在关注this example code

初始化无权访问列表存储桶的源凭证:

from google.oauth2 import service_acccount

target_scopes = [
    'https://www.googleapis.com/auth/devstorage.read_only']

source_credentials = (
    service_account.Credentials.from_service_account_file(
        '/path/to/svc_account.json',
        scopes=target_scopes))

现在使用源凭据获取凭据以模拟另一个服务帐户:

from google.auth import impersonated_credentials

target_credentials = impersonated_credentials.Credentials(
  source_credentials=source_credentials,
  target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
  target_scopes = target_scopes,
  lifetime=500)
google-cloud-platform impersonation service-accounts google-iam google-cloud-iam
1个回答
1
投票

而不是尝试从用户帐户模拟服务帐户,而是向用户授予创建服务帐户OAuth访问令牌的权限。

向用户授予服务帐户上的角色roles/iam.serviceAccountTokenCreator

调用API generateAccessToken以从服务帐户创建访问令牌。

projects.serviceAccounts.generateAccessToken

简单的HTTP POST请求将返回访问令牌。使用服务帐户的电子邮件地址修改以下请求。

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/[email protected]:generateAccessToken

请求正文:

{
  "delegates": [],
  "scope": [
      "https://www.googleapis.com/auth/cloud-platform"
  ],
  "lifetime": "3600s"
}

此API需要授权。在HTTP授权标头中包含用户的OAuth访问令牌。

Authorization: Bearer ACCESS_TOKEN

响应正文:

{
   "accessToken": "eyJ0eXAifeA...NiK8i",
   "expireTime": "2020-03-05T15:01:00.12345678Z"
}
© www.soinside.com 2019 - 2024. All rights reserved.