使用 nodejs 从 Azure Keyvault 获取 Secret

Get Secret from Azure Keyvault using nodejs

我需要读取 Azure 活动目录中的用户列表。客户创建了一个 Graph API 应用程序,但他们不想共享该应用程序的客户端机密,而是要求我们使用 Key vault。如何从 node.js 应用程序访问检索用户列表的密钥?

我尝试了下面的方法,但出现错误,我不确定如何进行身份验证。

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

const credential = new DefaultAzureCredential();

const vaultName = "lsm-keyvault";
const url = `https://${vaultName}.vault.azure.net`;

const client = new SecretClient(url, credential);

const secretName = "Demo";

async function main() {
  const result = await client.setSecret(secretName, "MySecretValue", {
    enabled: false
  });

  console.log(result)
}

您只需按照以下步骤操作即可:

  • 根据应用注册在 Azure Active Directory(服务主体)中创建应用。
  • 转到 Key Vault 资源、访问策略边栏选项卡,为我们在上述步骤中创建的这个 Azure AD 应用程序(服务主体)分配读取访问权限。
  • 在您的应用服务中设置这 3 个环境变量 AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET。从我们在步骤 1 中创建的应用中获取这些变量的值。
  • 使用我们现在已经在使用的DefaultAzureCredential。这将自动从我们在应用服务中定义的环境变量中选择凭据进行身份验证。

另一种方法是动态获取 Key Vault 令牌并使用该令牌从 Key Vault 中获取机密 - https://docs.microsoft.com/en-us/samples/azure-samples/app-service-msi-keyvault-node/app-service-msi-keyvault-node/

有用参考:

嗯,如果你运行本地代码,DefaultAzureCredential会自动使用环境变量。

因此,在您的情况下,您需要 register an application with Azure AD, and get the tenant id, client id(i.e. application id), client secret(i.e. application secret), set the environmental variablesAZURE_CLIENT_IDAZURE_CLIENT_SECRETAZURE_TENANT_ID

对于您遇到的403错误,我注意到您说的是It added as a compound entity,根据我的经验,您没有将与AD App相关的正确服务主体正确添加到Access policies密钥库。如果添加正确,它将显示为APPLICATION,而不是COMPOUND IDENTITY

所以你在添加的时候直接搜索client Id(i.e. application Id)或者the name of your App Registration,确保你添加的是正确的。我在这个里面说的很详细,你可以参考

retrieve the secretGet权限就够了,代码应该是

const retrievedSecret = await client.getSecret(secretName);

我注意到你在你的代码中使用了client.setSecret,它被用来save a secret,要使用它,你可能需要Set权限。

有关详细信息,请参阅 Quickstart: Azure Key Vault client library for Node.js (v4)

更新:

I have to eventually need to deploy this but not in azure but in another environment. How do I set the environment variables and access it.

如果是这样,你需要更改代码进行身份验证,直接在代码中使用这三个值。

换行

const { DefaultAzureCredential } = require("@azure/identity");
const credential = new DefaultAzureCredential();

const { ClientSecretCredential } = require("@azure/identity");
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

参见 - https://www.npmjs.com/package/@azure/identity/v/1.0.3#authenticating-as-a-service-principal