如何在部署的代码中使用服务帐户?

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

我已使用 IAMCredentialsClient 为项目上的服务帐户生成访问令牌

  const client = new IAMCredentialsClient();
  const [token] = await client.generateAccessToken({
    name: 'projects/-/serviceAccounts/my-service-accou[email protected]',
    scope: SCOPES,
  });

这已成功通过身份验证,因为我现在拥有访问令牌。

我还使用

gcloud auth application-default login --impersonate-service-account [email protected]
允许在本地作为服务帐户运行。

要在本地初始化 API 客户端,我可以执行以下操作:

    const auth = new google.auth.GoogleAuth({
        keyFile: '../AppData/Roaming/gcloud/application_default_credentials.json',
        scopes: ['https://www.googleapis.com/auth/spreadsheets'],
      });
    const sheets = google.sheets({version: 'v4', auth});

这可以在本地运行,但我计划将该应用程序容器化,然后使用 Cloud Run 进行部署。显然使用 keyFile 和文件路径是行不通的。我如何以生产代码知道使用服务帐户的方式编写代码?

node.js google-api-nodejs-client google-iam
1个回答
0
投票

Google Cloud Run 有一个默认服务帐户和元数据服务。您可以从元数据服务请求访问令牌。

在您的帖子中,您正在冒充服务帐户。您可以附加所需的任何服务账户,将 IAM 角色分配给该服务账户,然后请求访问令牌。无需涉及模拟,这将需要更多的权限。

查看本指南,了解有关 Cloud Run 服务身份的更多详细信息:

Google Cloud Run 服务身份

© www.soinside.com 2019 - 2024. All rights reserved.