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
Use the below code to get Azure KeyVault token value from
appsettings.json
.It works for both Azure KeyVault secrets and localappsettings.json
Retrieve token in Controller and display in
.cshtml
HomeController.cs
.cshtml
Output
Update
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