You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@google-cloud/storage访问GCS除服务账号密钥外的授权方式咨询

@google-cloud/storage 非服务账号密钥的身份验证方案

@google-cloud/storage 作为GCP官方维护的Node.js客户端库,默认遵循Google Application Default Credentials (ADC) 全局认证链路,所有符合ADC规范的认证方式都可以直接使用,不需要在Storage构造函数中做特殊适配,你提到的Workload Identity Federation也完全支持,无需额外的构造参数。

以下是几种常用的无服务账号密钥的认证方案:

  • 运行在GCP内部资源时使用绑定服务账号
    如果你的代码部署在GCE、GKE、Cloud Run、Cloud Functions等GCP原生计算资源上,只需要提前给对应资源绑定拥有GCS访问权限的服务账号,不需要配置任何密钥文件或环境变量,直接初始化即可:
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({
  projectId: 'my_google_project_id'
});

客户端库会自动从资源的元数据服务获取临时访问令牌,全程不需要处理长期密钥。

  • 使用Workload Identity Federation
    该方案完全适配现有@google-cloud/storage版本,不需要修改Storage初始化代码:
  1. 提前通过gcloud CLI生成Workload Identity Federation的凭证配置文件
  2. 将环境变量GOOGLE_APPLICATION_CREDENTIALS指向该配置文件路径
  3. 直接使用无参构造初始化Storage即可:
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();

底层认证库会自动按照联邦身份的流程获取访问凭证,不需要暴露服务账号密钥。

  • 使用用户OAuth2令牌认证
    如果是面向个人用户的访问场景,可以直接传入OAuth2认证客户端实例进行认证,不需要使用服务账号:
const {Storage} = require('@google-cloud/storage');
const {OAuth2Client} = require('google-auth-library');

const oauth2Client = new OAuth2Client(
  'YOUR_CLIENT_ID',
  'YOUR_CLIENT_SECRET',
);
oauth2Client.setCredentials({
  refresh_token: 'YOUR_USER_REFRESH_TOKEN'
});

const storage = new Storage({
  projectId: 'my_google_project_id',
  authClient: oauth2Client
});
  • 模拟服务账号认证
    如果你需要用现有身份模拟指定服务账号访问GCS,不需要获取目标服务账号的密钥,直接配置模拟参数即可:
const {Storage} = require('@google-cloud/storage');
const storage = new Storage({
  projectId: 'my_google_project_id',
  authClientOptions: {
    credentials: {
      /* 你的现有身份凭证 */
    },
    impersonateServiceAccount: 'target-service-account@example.iam.gserviceaccount.com'
  }
});

方案选择建议

  1. 代码运行在GCP内部环境:优先选择资源绑定服务账号方案,零密钥配置安全性最高
  2. 代码运行在非GCP环境:优先选择Workload Identity Federation方案,避免长期留存服务账号密钥
  3. 个人用户访问场景:选择OAuth2用户令牌认证方案

内容的提问来源于stack exchange,提问作者Vladimir Pimtchenkov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:30:02