Azure 应用程序配置和 Key Vault 中存储的值是否不仅在后端 API 服务器中加载和使用,还在前端(例如移动应用程序和网站)中加载和使用?
这是一个简单的问题,但我在Azure官方文档中找不到有关此用例的信息。
因此,您可以使用如下方式在后端代码中加载 KeyVault Secret:
SecretClientOptions options = new SecretClientOptions()
{
Retry =
{
Delay= TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
};
var client = new SecretClient(new Uri("https://<your-unique-key-vault-
name>.vault.azure.net/"), new DefaultAzureCredential(),options);
KeyVaultSecret secret = client.GetSecret("<mySecret>");
string secretValue = secret.Value;
取决于您调用此函数的位置以及保存到的变量将决定可用的位置。对于前端,例如 Javascript(我不是前端开发人员)使用如下内容:
const { SecretClient } = require("@azure/keyvault-secrets");
const { DefaultAzureCredential } = require("@azure/identity");
async function main() {
// If you're using MSI, DefaultAzureCredential should "just work".
// Otherwise, DefaultAzureCredential expects the following three
environment variables:
// - AZURE_TENANT_ID: The tenant ID in Azure Active Directory
// - AZURE_CLIENT_ID: The application (client) ID registered in the AAD tenant
// - AZURE_CLIENT_SECRET: The client secret for the registered application
const credential = new DefaultAzureCredential();
const keyVaultName = process.env["KEY_VAULT_NAME"];
if(!keyVaultName) throw new Error("KEY_VAULT_NAME is empty");
const url = "https://" + keyVaultName + ".vault.azure.net";
const client = new SecretClient(url, credential);
// Create a secret
// The secret can be a string of any kind. For example,
// a multiline text block such as an RSA private key with newline characters,
// or a stringified JSON object, like `JSON.stringify({ mySecret: 'MySecretValue'})`.
const uniqueString = new Date().getTime();
const secretName = `secret${uniqueString}`;
const result = await client.setSecret(secretName, "MySecretValue");
console.log("result: ", result);
// Read the secret we created
const secret = await client.getSecret(secretName);
console.log("secret: ", secret);
// Update the secret with different attributes
const updatedSecret = await client.updateSecretProperties(secretName, result.properties.version, {
enabled: false
});
console.log("updated secret: ", updatedSecret);
// Delete the secret immediately without ability to restore or purge.
await client.beginDeleteSecret(secretName);
}
main().catch((error) => {
console.error("An error occurred:", error);
process.exit(1);
});
您还可以通过在 Web 应用程序的配置中执行类似操作,将 KeyVault 数据直接添加到 Azure WebApp appSettings 中。所有这些都需要正确设置 KeyVault 的安全性和网络访问才能发挥作用。