Thanks @ consultwithmike for the code
Install the below NuGet packages.
Azure.Extensions.AspNetCore.Configuration.Secrets
Azure.Identity
My .csproj
file
<ItemGroup>
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.2.2" />
<PackageReference Include="Azure.Identity" Version="1.8.2" />
</ItemGroup>
My Program.cs
file
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
var builder = WebApplication.CreateBuilder(args);
var Env = builder.Environment.EnvironmentName;
builder.Configuration
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{Env}.json", optional: true, reloadOnChange: true);
builder.Services.AddControllersWithViews();
var app = builder.Build();
var keyVault = builder.Configuration["KeyVault:URI"];
var credential = new DefaultAzureCredential();
var secretClient = new SecretClient(new Uri(keyVault), credential);
var secretValue = await secretClient.GetSecretAsync("mySecrets");
var conn = builder.Configuration["ConnectionStrings:MyKVConn"];
var conn1 = builder.Configuration.GetConnectionString("MyKVConn");
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapGet("/", () => secretValue);
app.Run();
My appsettings.json
file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"KeyVault": {
"URI": "https://KeyVaultName.vault.azure.net/"
},
"ConnectionStrings": {
"MyKVConn": "@AzureKeyVault(mySecrets)"
},
"AllowedHosts": "*"
}
- Provide the necessary permissions to the
Azure Key Vault
.


