Tuesday, May 16, 2023

Pass Azure KeyVault Secret to Database Settings configuration

 To inject the KeyVault secret into the DatabaseSettings object

#1 You can write down the code as follow in program.cs file , configuration method 

var keyVaultEndPoint = new Uri(builder.Configuration["VaultKey"]); var secretClient = new SecretClient(keyVaultEndPoint, new DefaultAzureCredential()); KeyVaultSecret kvs = secretClient.GetSecret(builder.Configuration["SecretName"]); string connectionString = kvs.Value; builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor() .AddMicrosoftIdentityConsentHandler(); builder.Services.Configure<DatabaseSettings>(options => { options.ConnectionString = connectionString; builder.Configuration.GetSection("Database").Bind(options); }); builder.Services.AddSingleton<TodoService>(); builder.Services.AddSingleton<RecipesService>(); builder.Services.AddSingleton<SpecialDatesService>();


#2. Modify the DatabaseSettings class in your appsettings.json file:


"Database": { "ConnectionString": "", "DatabaseName": "Personal", "TodoCollectionName": "todo", "RecipesCollectionName": "recipes", "SpecialDatesCollectionName": "specialdates" }


By binding the DatabaseSettings options, you can set the ConnectionString property using the retrieved value from the KeyVault secret while keeping the rest of the configuration intact.


Now, when you inject the DatabaseSettings object into your services, the ConnectionString property will be populated with the secret value from Azure Key Vault.

No comments:

Post a Comment

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...