简体   繁体   中英

Using Azure Managed Identity for app deployed to Azure?

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?

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)

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM