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

Node.js中使用非默认凭据认证GCP Secret Manager客户端

使用指定服务账号认证Google Secret Manager客户端

有两种方式可以实现用指定服务账号而非默认凭据初始化Secret Manager客户端:

方法一:直接传入服务账号凭据(推荐)

SDK支持直接在初始化客户端时传入服务账号密钥文件路径或解析后的JSON对象,无需手动创建JWT实例:

import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
import fs from 'fs';
import path from 'path';

// 方式A:传入密钥文件路径
const smClient = new SecretManagerServiceClient({
  keyFilename: path.resolve(__dirname, '../service-account.json')
});

// 方式B:传入解析后的密钥JSON对象
const keyFile = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../service-account.json')));
const smClient = new SecretManagerServiceClient({
  credentials: keyFile
});

方法二:传入手动创建的JWT认证客户端

如果需要自定义JWT配置(比如指定特殊权限范围),可以将自己创建的JWT实例通过authClient参数传入:

import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
import { JWT } from 'google-auth-library';
import fs from 'fs';
import path from 'path';

const keyFile = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../service-account.json')));

const authClient = new JWT({
  email: keyFile.client_email,
  key: keyFile.private_key,
  scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});

const smClient = new SecretManagerServiceClient({
  authClient: authClient
});

两种方式都能让客户端使用指定的服务账号完成认证,第一种方式更简洁,是官方推荐的常规用法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:03:15