Pet*_*ter 5 c# dependency-injection asp.net-web-api azure-keyvault .net-6.0
我创建了一个实体框架 DbContext,并在程序中对其进行初始化(.NET 6 中不再需要 Startup.cs)。连接字符串取决于 Azure Key Vault 内的 SQL 密码。因此 Key Vault 和 DbContext 的注册都是在 Program.cs 中完成的。但是如何从 KeyVault 检索秘密并将其放入连接字符串中?我不想在这里手动创建 SecretClient 实例,但以某种方式注入它......
我现在有:
builder.Services.AddAzureClients(clientBuilder =>
{
clientBuilder.AddSecretClient(new Uri(builder.Configuration.GetSection("KeyVault:VaultUri").Value))
.WithCredential(new DefaultAzureCredential());
});
builder.Services.AddDbContext<MyContext>(options =>
{
// How to get an instance of SecretClient here via DI? I need to call the serviceClient.GetSecret("sql-password") here to put it inside the connectionstring
// var sqlPassword = builder.Configuration.GetSection("sql-password").Value <-- also returns null
var sqlPassword = "get-this-password-from-key-vault";
options.UseSqlServer(string.Format(builder.Configuration.GetConnectionString("MyConnectionString"), sqlPassword));
});
Run Code Online (Sandbox Code Playgroud)
我在几篇博客上读到,当您将 SecretClient 添加到服务时,它应该读取所有机密并将它们添加到 builder.Configuration 中,这意味着您应该能够像这样读取它:
var sqlPassword = builder.Configuration["sql-password"]
Run Code Online (Sandbox Code Playgroud)
或者
var sqlPassword = builder.Configuration.GetSection("sql-password").Value
Run Code Online (Sandbox Code Playgroud)
它们都返回null。所以我已经没有选择了。如果有人能解决这个简单的问题,我将非常感激。谢谢!
PS:我知道Key Vault已成功注册;当我在控制器中使用 ServiceClient 时,我可以成功检索密钥。
您可以通过https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/extensions/Microsoft.Extensions.Azure/README.mdSecretClient中描述的多种方式进行注册。在这种情况下,您甚至可以实例化一个,将其添加到配置生成器,然后直接使用它。或者,注册到配置生成器后,请参阅存储在以下文件中的所需配置值:SecretClientSecretClient
var builder = WebApplication.CreateBuilder(args);
var keyVaultEndpoint = new Uri(Environment.GetEnvironmentVariable("VaultUri"));
builder.Configuration.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());
// Add services to the container.
builder.Services.AddDbContext<MyContext>(options =>
{
var sqlPassword = builder.Configuration["secret-password"];
options.UseSqlite(string.Format(builder.Configuration.GetConnectionString("MyConnectionString"), sqlPassword));
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,在 Key Vault 中,只需添加一个名为“secret-password”的机密。
| 归档时间: |
|
| 查看次数: |
12978 次 |
| 最近记录: |