0

I'm using Azure Key Vaults to keep my connection strings safe. It's work well when I'm using just one appsettings.json file, but when I changed it to enviornment divided aproach, I receave an error message saying the connection string was not initialized, as the key vaults doesn't be download from server.

How to configure it correctly?

1 Answers1

0

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.

enter image description here

enter image description here

enter image description here

Harshitha
  • 3,784
  • 2
  • 4
  • 9