user648931
user648931

Reputation: 523

How to read key vault secrets through IConfiguration object in local development in Azure web app

I've created a service principal for my local development through the AzureServicesAuthConnectionString environment variable and granted that principal access to the keyvault. However, when I read configuration["secret"] for a secret in key vault, it is null, and if I inspect the providers in the configuration object, I don't see a keyvault provider, only json providers for my appsettings files. Is there a step that I'm missing?

Upvotes: 0

Views: 1495

Answers (2)

Joey Cai
Joey Cai

Reputation: 20067

I create a .net core webapp and test well in my site. Here is the code you could refer to.

In Program.cs:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder =>
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient =new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                builder.AddAzureKeyVault("https://yourkeyvaultname.vault.azure.net/",
                keyVaultClient, new DefaultKeyVaultSecretManager());
        })
        .UseStartup<Startup>();

In HomeController.cs:

 private readonly IConfiguration _configuration;
 public HomeController(IConfiguration configuration)
 {
     _configuration = configuration;
 }
 public IActionResult Index()
 {
     ViewBag.Secret = _configuration["yoursecretname"];
     return View();
 }

The snapshot:

enter image description here

For more details, you could refer to this article.

Upvotes: 1

C B
C B

Reputation: 2000

You can try the new feature we have to just pump the secret into the App Settings directly.

Here is the blog to show how to set that up. It is easy and works via Template deployments as well.

https://learn.microsoft.com/en-us/azure/app-service/app-service-key-vault-references

Upvotes: 1

Related Questions