How do I access my Azure Key Vault’s "secrets" locally, to be used as environment variables?
I have an integration test application which loads some secrets from a Settings.runsettings
file where the secrets are currently defined as Environment Variables. My Settings.runsettings
file currently looks like this:
<RunSettings>
<RunConfiguration>
.....
<EnvironmentVariables>
<MySecret>this needs to be removed and replaced with an Azure Key Vault secret reference</MySecret>
</EnvironmentVariables>
....
</RunConfiguration>
</RunSettings>
I need to remove all secrets from source control, so the ‘value’ of MySecret
needs to be replaced with a secret reference from my Azure Key Vault. I checked this reference but it’s not clear to me how exactly I’m supposed to reference my Azure Key Vault and get the value of "MySecret" for app startup in my Settings.runsettings
file.
2
Answers
I would consider using the built in User Secrets feature in Visual Studio
(right-click on your project to activate it)
read more about it here:
https://learn.microsoft.com/en-us/dotnet/architecture/microservices/secure-net-microservices-web-applications/developer-app-secrets-storage
That’s the right thing to do, you are doing a great job! Secrets could be read from multiple possible sources based on your use case, like App Configuration, from Environment or in case of development environment, from Visual Studio User Secrets. However, indeed the ideal storage for secrets is the KeyVault. You can also load secrets directly from KeyVault at startup.
The best way to access KeyVault from your app startup is to use
Managed Identity
, where the Managed Identity will have authorization to read from the vault. However, this works only when your app is running in Azure and it wont work in local machine development environment as there is noManaged Identity
.Visual Studio User Secrets is one solution for this case, however, it is not very scalable as the secrets need to be copied to each developer’s local machine.
To resolve this issue, Microsoft has introduced the
AzureCliCredential
class, which will authorize with your Azure CLI identity ( the one you login withaz login
).So, to make things work, you have to use
ManagedIdentityCredential
when your app is running in Azure andAzureCliCredential
when app is in development environment. To make this happen, you can use theChainedTokenCredential
wrapper.When you run the app in Azure, it will use
ManagedIdentityCredential
and in development since there is no managed identity, it will fall back toAzureCliCredential
.Don’t forget to add the NuGets: