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

时间:2020-03-05 22:14:37

标签: google-cloud-platform impersonation service-accounts google-iam google-cloud-iam

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

用户可以直接模拟服务帐户吗?如果可以,怎么办?

我正在关注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)

2 个答案:

答案 0 :(得分:3)

是的,您可以模拟用户到服务帐户。您只需要确保您的用户对目标服务帐户具有Service Account Token Creator角色。 您需要通过以下方式明确授予它:

  1. 在IAM和管理中选择服务帐户
  2. 选择IAM
  3. 选择您的帐户和您自己作为上述角色(服务帐户令牌创建者)。

即使您是项目负责人,也不会削减费用。

请注意,权限申请可能需要1-2分钟,因此,如果您的代码在以下位置出错:

Unable to acquire impersonated credentials...

请确保您具有上述许可,如果您刚刚添加了该许可,请稍候,然后重试:)

代码实际上保持不变,这是来自文档的改编示例:

import google.auth
import google.auth.impersonated_credentials
from google.cloud import storage


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

creds, pid = google.auth.default()
print(f"Obtained default credentials for the project {pid}")
tcreds = google.auth.impersonated_credentials.Credentials(
    source_credentials=creds,
    target_principal="<target service account email>",
    target_scopes=target_scopes,
)

client = storage.Client(credentials=tcreds)
buckets = client.list_buckets(project=pid)
for bucket in buckets:
    print(bucket.name)

答案 1 :(得分:2)

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

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

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

projects.serviceAccounts.generateAccessToken

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

POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/SERVICE-ACCOUNT-NAME@PROJECTID.iam.gserviceaccount.com: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"
}
相关问题