skip to Main Content

I’m getting a token from Azure KeyVault. I setup the keyvault in Program.cs file. It works as long as the Azure account in Visual Studio got access. obviously once that account doesn’t have access, an error is thrown.

How do I skip setting up the key vault in case it’s development env AND get token value from appsettings.json? I don’t want the app to fail because the account is not authorized and also get token value provided by the user in appsettings.json.

  public class Program
  {
    public static void Main(string[] args)
    {
      CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
              webBuilder.UseStartup<Startup>();
            })

      .ConfigureAppConfiguration((context, config) =>
      {
        var builtConfig = config.Build();
        var vaultConfigSection = builtConfig.GetSection("AzureOne");
        var vaultUri = vaultConfigSection.GetValue<string>("KeyVaultUri");
        var secretClient = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential());
        config.AddAzureKeyVault(secretClient, new KeyVaultSecretManager());
      });
    }

my appsettings.json look like this

{
  "EndPoints": {
    "EndpointOne": "https://awesome.net"
  },
  "AzureOne": {
    "TokenToBeUsedInDev": "4234-fake-234234-fake",
    "KeyVaultUri": "https://myKeyVaultName.vault.azure.net/"
  },
}

I’m using .NET 5

2

Answers


  1. Use the below code to get Azure KeyVault token value from appsettings.json.It works for both Azure KeyVault secrets and local appsettings.json

    using Azure.Extensions.AspNetCore.Configuration.Secrets;
    using Azure.Identity;
    using Azure.Security.KeyVault.Secrets;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace KVLocalTest
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    })
                        .ConfigureAppConfiguration((context, config) =>
                         {
                             var builtConfig = config.Build();                        
                             var vaultConfigSection = builtConfig.GetSection("AzureOne");
                             var vaultUri = vaultConfigSection.GetValue<string>("KeyVaultUri");
                             config.AddAzureKeyVault(new Uri(vaultConfigSection.GetValue<string>("KeyVaultUri")),
          new DefaultAzureCredential());                     
    
        }
    }
    

    Retrieve token in Controller and display in .cshtml
    HomeController.cs

    using KVLocalTest.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace KVLocalTest.Controllers
    {
        public class HomeController : Controller
        {
            private readonly IConfiguration Configuration;
            private readonly ILogger<HomeController> _logger;
    
            public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
            {
                _logger = logger;
                Configuration = configuration;
            }
    
            public IActionResult Index()
            {
                var vaultConfigSection = Configuration.GetSection("AzureOne");
                ViewBag.TokenLocal =  vaultConfigSection.GetValue<string>("TokenToBeUsedInDev");
                return View();
            }  
        }
    }
    
    

    .cshtml

    <h2>@ViewBag.TokenLocal</h2>
    

    Output

    enter image description here

    Update

    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
    var isDevelopment = environment == Environments.Development;
    
    if (!isDevelopment)
    {
      var vaultConfigSection = builtConfig.GetSection("AzureOne");
      config.AddAzureKeyVault(new Uri(vaultConfigSection.GetValue<string>("KeyVaultUri")),
           new DefaultAzureCredential());
    }
    
    Login or Signup to reply.
  2. How about creating a user managed identity in Azure. Then you assign that identity to access keyvault. You could use that identity in your code to get an access token and use it in your dev environment.
    https://learn.microsoft.com/en-us/azure/key-vault/general/authentication

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search