首页
/ Google Auth Library Node.js 中如何从 ExternalAccountClient 获取 GoogleAuth 对象

Google Auth Library Node.js 中如何从 ExternalAccountClient 获取 GoogleAuth 对象

2025-07-08 00:47:18作者:裘旻烁

在 Google Cloud 开发中,我们经常需要在不同服务之间进行身份验证。本文将详细介绍如何在 Node.js 环境中,使用 google-auth-library 库从 ExternalAccountClient 获取 GoogleAuth 对象,以便与 Cloud Run 后端服务进行安全通信。

背景知识

Google Auth Library 提供了多种身份验证方式,其中 ExternalAccountClient 是一种特殊类型的客户端,用于处理外部身份提供者的认证流程。而 GoogleAuth 是一个更高级别的抽象,可以包装各种 AuthClient 实现。

解决方案

方法一:使用 fromJSON 直接创建 GoogleAuth

最直接的方式是使用 GoogleAuth.fromJSON() 方法,该方法可以直接接收与 ExternalAccountClient.fromJSON() 相同的配置参数:

const {GoogleAuth} = require('google-auth-library');

const auth = GoogleAuth.fromJSON({
  type: "external_account",
  audience: `//iam.googleapis.com/projects/${GCP_PROJECT_NUMBER}/locations/global/workloadIdentityPools/${GCP_WORKLOAD_IDENTITY_POOL_ID}/providers/${GCP_WORKLOAD_IDENTITY_POOL_PROVIDER_ID}`,
  subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
  token_url: "https://sts.googleapis.com/v1/token",
  service_account_impersonation_url: `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${GCP_SERVICE_ACCOUNT_EMAIL}:generateAccessToken`,
  subject_token_supplier: {
    getSubjectToken: getVercelOidcToken,
  }
});

方法二:将 ExternalAccountClient 传递给 GoogleAuth

如果你已经创建了 ExternalAccountClient 实例,可以直接将其传递给 GoogleAuth 构造函数:

const {GoogleAuth, ExternalAccountClient} = require('google-auth-library');

const authClient = ExternalAccountClient.fromJSON({
  // 配置参数同上
});

const auth = new GoogleAuth({
  authClient: authClient,
  scopes: "https://www.googleapis.com/auth/cloud-platform",
  projectId: GCP_PROJECT_ID
});

获取 ID Token 访问 Cloud Run

获取到 GoogleAuth 实例后,就可以轻松获取 ID Token 来访问受保护的 Cloud Run 服务:

const idTokenClient = await auth.getIdTokenClient(backend_url);
const response = await idTokenClient.request({url: backend_url});

最佳实践

  1. 环境变量管理:建议将 GCP_PROJECT_NUMBER、GCP_WORKLOAD_IDENTITY_POOL_ID 等配置信息存储在环境变量中,而不是硬编码在代码里。

  2. 错误处理:添加适当的错误处理逻辑,特别是在获取和刷新令牌时。

  3. 令牌缓存:GoogleAuth 会自动管理令牌的缓存和刷新,无需手动处理。

  4. 最小权限原则:只为服务账户授予必要的最小权限,而不是使用过于宽泛的权限。

总结

通过上述方法,我们可以在 Node.js 应用中灵活地使用 ExternalAccountClient 和 GoogleAuth 来实现安全的服务间通信。这种方法特别适合在无服务器环境(如 Vercel)中与 Google Cloud 服务进行集成,既保证了安全性,又简化了身份验证流程。

登录后查看全文
热门项目推荐
相关项目推荐