Connection to Azure Vault using MSI
- Enable Managed Service Identity in the Configuration blade under your virtual machine.
- Search for NameOfYourVM service principal and add it to your Key Vault under Access Policies. Add key/secret/certificate permissions.
- On your Azure VM, run the console app.
class Program
{
// Target C# 7.1+ in your .csproj for async Main
static async Task Main()
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient.GetSecretAsync(
"https://VAULT-NAME.vault.azure.net/secrets/SECRET-NAME");
Console.WriteLine(secret.Value);
Console.ReadLine();
}
}
To run locally, create your very own Azure AD application registration (Web App/Web API type to make it a confidential client), add it to Key Vault and use its client_id and client_secret when acquiring the access token —
https://docs.microsoft.com/en-us/azure/key-vault/key-vault-use-from-web-application#gettoken
As Varun mentioned in the comments, there's now a better way to get an access token when running locally without exposing a service principal —
https://docs.microsoft.com/en-us/azure/key-vault/service-to-service-authentication#local-development-authentication
To run locally.
- install Azure Cli
- Open Windows Powershell
- write
az login
command (it will give an url and code ) - Open Url and enter the code which is given with az login
then get the secret value like this
var secret = keyVaultClient.GetSecretAsync("https://VAULT-NAME.vault.azure.net/secrets/SECRET-NAME").GetAwaiter().GetResult() ;
secret.Value; //will be your secret.
a correct answer is already given above, here's an additional one :-)
Azure MSI applying with App Service & Vault
Enable System Assigned Managed Identity for your App Service, check Identity section under settings.
Add Policy under Vault
configure your code behind