Home > OS >  Using Azure Managed Identity for app deployed to Azure?
Using Azure Managed Identity for app deployed to Azure?

Time:12-07

I have an azure function app that will be deployed to azure. In this app, I have some secrets which are stored in Key Vault which I need to make use of using Azure Managed Identity. I have the following method in one of my classes which retrieves the secrets stored on KeyVault.

public static string GetSecretValue(string secretkey)
        {
            string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
            var kvUri = "https://"   keyVaultName   ".vault.azure.net";
            var secretclient = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
            return secretclient.GetSecret(secretkey).Value.Value;
        }

I have an environment variable which stores my Key vault name as shown in the code. What I need is to check if my steps are correct in order to use Azure Managed Identity to retrieve the values of the 5 secrets stored in KeyVault during production/deployment to Azure and make sure everything works well (Note that when running locally everything works perfectly).

What I did so far is the following:

1- Enabled Managed Identities for Azure Function App

2- Grant Permission to Azure Function (selecting it as a user principal) to access KeyVault

3- Configured the Azure Key Vault in Visual Studio based on the method shown above

My question am I missing something in the code above or in the steps in order to use Azure Managed Identities? Should I add anything else in the Application Settings on Azure or that is not necessary? Can I keep the Environment Variable the way it is shown or should I store it somewhere else on Azure ?

CodePudding user response:

I have tested in my environment.

You need to add the application setting with the value as below for each secrets:

@Microsoft.KeyVault(SecretUri=https://my-key-vault.vault.azure.net/secrets/secretName/secretVersion)

enter image description here

You can find the secret Uri from the secret identifier of current version of the secret:

enter image description here

I called the secret using below line of code:

var secretValue = Environment.GetEnvironmentVariable("secret1", EnvironmentVariableTarget.Process);  

I am able to fetch the key vault secrets successfully

enter image description here

  • Related