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

如何在Node.js中用客户端ID和密钥认证Azure Key Vault并获取密钥

使用客户端ID和密钥认证Azure Key Vault(Node.js)

你需要用ClientSecretCredential替代DefaultAzureCredential,这是Azure SDK专门为**服务主体(客户端ID+密钥)**设计的认证方式,具体实现如下:

1. 确认依赖安装

确保已安装所需的Azure SDK包:

npm install @azure/identity @azure/keyvault-secrets

2. 修改认证代码

替换原代码中的DefaultAzureCredential为ClientSecretCredential,需要传入三个核心参数:Azure AD租户ID、服务主体的客户端ID、服务主体的客户端密钥:

const { ClientSecretCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");

// 替换为你的实际信息
const tenantId = "<你的Azure AD租户ID>";
const clientId = "<你的服务主体客户端ID>";
const clientSecret = "<你的服务主体客户端密钥>";

// 初始化客户端密钥认证实例
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

// Key Vault地址
const vaultName = "web-designer";
const url = `https://${vaultName}.vault.azure.net`;

// 创建SecretClient并获取密钥
const client = new SecretClient(url, credential);
const secretName = "web-designer-secret";

client.getSecret(secretName)
  .then((res) => {
    console.log("密钥完整信息:", res);
    // 若仅需密钥值,可直接打印res.value
    console.log("密钥值:", res.value);
  })
  .catch((err) => {
    console.error("获取密钥失败:", err);
  });

关键注意事项

  • 权限配置:必须确保你的服务主体在Azure Key Vault的访问策略中被授予Secrets/Get权限,否则会返回权限不足的错误。
  • 安全最佳实践:不要将租户ID、客户端ID、客户端密钥硬编码到代码中,建议通过环境变量读取:
    const tenantId = process.env.AZURE_TENANT_ID;
    const clientId = process.env.AZURE_CLIENT_ID;
    const clientSecret = process.env.AZURE_CLIENT_SECRET;
    
  • 关于ManagedIdentityCredential:这个认证方式仅适用于Azure托管环境(如App Service、VM等),需要在对应资源上启用系统/用户托管标识,和你当前需要的客户端ID+密钥认证场景不匹配,所以之前使用无效是正常的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:45:34