Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Key Vault settings to class

In ASP.NET Core, if reading configuration from a JSON app.settings file I can bind a section to an object like this:

services.Configure<MyPocoConfig>(Configuration.GetSection("Section"))

Is there a straightforward way to do this with a group of settings that are read from Azure Key Vault? I am following the guide as described in the MSDN documentation here https://docs.microsoft.com/en-us/azure/key-vault/vs-key-vault-add-connected-service#access-your-secrets-in-code

I can manually map them like this:

services.Configure<MyPocoConfig>(myPoco =>
                {
                    myPoco.Option1 = Configuration["Option1"];
                    myPoco.Option2 = Configuration["Option2"];
                });

I just wondered if there was a way to automap them as it works for config stored in app.settings JSON. I'm sure it could be done with reflection but I was hoping there'd be a built in way.

I tried putting the settings into a category using the category--setting syntax described in the article and reading them with services.Configure<MyPocoConfig>(Configuration.GetSection("category")), but this doesn't work.

Edit:

It is now possible as of 2020 to put settings into a category using the category--setting syntax and read them like services.Configure<MyPocoConfig>(Configuration.GetSection("category"))

like image 474
zola25 Avatar asked Mar 16 '19 20:03

zola25


People also ask

How do I add a key vault reference in app config?

Add a Key Vault reference to App ConfigurationSelect All resources, and then select the App Configuration store instance that you created in the quickstart. Select Configuration Explorer. Select + Create > Key vault reference, and then specify the following values: Key: Select TestApp:Settings:KeyVaultMessage.

How do I set a private endpoint for key vault?

Select the key vault from the list to which you want to add a private endpoint. Select the "Networking" tab under Settings. Select the "Private endpoint connections" tab at the top of the page. Select the "+ Create" button at the top of the page.


1 Answers

You can achieve the same by naming your Secret in the following pattern.

 Section--Option1
 Section--Option2

And you can use the following to get the values by section and .NetCore automatically maps it.

services.Configure<MyPocoConfig>(Configuration.GetSection("Section"))

Refer link https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-2.2#bind-an-array-to-a-class

like image 160
Naveen R Kumar Avatar answered Nov 16 '22 18:11

Naveen R Kumar