如何使用 Azure.Identity 和 Azure.Security.KeyVault.Secrets 库对 Azure Key Vault 进行身份验证和检索机密?我正在尝试从我的 Azure Key Vault 中获取一些机密。为了实现这一目标,我正在利用 Azure.Security.KeyVault.Secrets 和 Azure.Identity 库。鉴于我的经验有限,我的方法涉及使用凭据:appId、appkey 和tenantId 进行身份验证,然后检索存储在Azure Key Vault 中的4 个机密。然而,在执行像await GetSecretValueAsync(client, "secret_name")这样的行时,我的应用程序似乎无限期地挂起而不会引发异常。输出只是指出:“程序‘[4212] iisexpress.exe’已退出,代码为 4294967295 (0xffffffff)。”我犯了什么错误吗?要使用这些凭据成功进行身份验证并检索机密,还需要执行哪些额外步骤?
using System;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
namespace Helpers
{
public class KeyVaultHelper
{
public static async Task<EntitySettings> GetCurrencyAllianceKeyVaultValue()
{
try
{
string keyVaultUrl = "my_url";
var appId = ConfigurationManager.AppSettings["APP_ID"];
var appKey = ConfigurationManager.AppSettings["APP_KEY"];
var tenantId = ConfigurationManager.AppSettings["TENANT_ID"];
var credential = new ClientSecretCredential(tenantId, appId, appKey);
var client = new SecretClient(new Uri(keyVaultUrl), credential);
var secret1 = await GetSecretValueAsync(client, "secret_name");
var secretKey = await GetSecretValueAsync(client, "secret_name");
var clientId = await GetSecretValueAsync(client, "secret_name");
var clientSecret = await GetSecretValueAsync(client, "secret_name");
return new EntitySettings
{
secret1 = publicKey,
secret2 = secretKey,
secret3 = clientId,
secret4 = clientSecret
};
}
catch (Exception ex)
{
throw;
}
}
private static async Task<string> GetSecretValueAsync(SecretClient client, string secretName)
{
KeyVaultSecret secret = await client.GetSecretAsync(secretName);
return secret.Value;
}
}
}
正如 @Daredevil 指出的那样,通常建议大多数库和许多应用程序(包括 Web 应用程序)调用
ConfigureAwait(false)
。
我确实想指出一些示例,以便使用配置提供程序在 ASP.NET 中更有效地使用 Key Vault SDK。
DefaultAzureCredential
,它可以使用您可以为本地开发设置的环境变量,但针对在 Azure 中托管进行了优化以使用托管身份,这更加安全。
因为您在本地使用配置变量,所以您可以使用:
TokenCredential credential = null;
if (app.Environment.IsDevelopment())
{
credential = new ClientSecretCredential(/*like you configured above*/);
}
else
{
credential = new DefaultAzureCredential();
}
通常,如果您在开发或生产中使用环境变量,则
DefaultAzureCredential
就是您所需要的,但仍然建议在生产中使用托管身份。