Here is an example of how to connect and fetch a secret from Azure Key Vault using a managed identity in an Azure App Service:
- First, you need to create a managed identity for your Azure App Service. You can do this by going to the App Service in the Azure portal, navigating to the “Identity” tab, and turning on the “System assigned” managed identity.
- Next, you need to grant the managed identity access to your Key Vault. You can do this by going to your Key Vault in the Azure portal, navigating to the “Access policies” tab, and adding a new access policy. In the “Select principal” section, search for the managed identity you created in step 1 and give it the “Get” permission for secrets.
- Configuring the following App Service settings:
VAULT_URL
: The URL of the Key Vault.SECRET_NAME
: The name of the secret that you want to fetch from the Key Vault.
- Once the managed identity has been granted access to the Key Vault, you can use the Azure Identity library to authenticate and fetch the secret. In your App Service code, you can add the following code snippet to fetch a secret
Sample Code – Python
import os
from azure.identity import ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient
vault_url = os.environ["VAULT_URL"]
secret_name = os.environ["SECRET_NAME"]
credential = ManagedIdentityCredential()
client = SecretClient(vault_url=vault_url, credential=credential)
secret = client.get_secret(secret_name)
print(secret.value)
Sample Code – .NET
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Threading.Tasks;
public class KeyVaultHelper
{
public static async Task<string> GetSecret(string secretName)
{
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
azureServiceTokenProvider.KeyVaultTokenCallback));
var secret = await keyVaultClient.GetSecretAsync(secretName)
.ConfigureAwait(false);
return secret.Value;
}
}
In this example, the GetSecret
method of the KeyVaultHelper
class fetches a secret from Azure Key Vault using an instance of KeyVaultClient
which is created using the AzureServiceTokenProvider
class. The GetSecretAsync
method of KeyVaultClient
is used to fetch the secret from the keyvault.
You can call this method by passing the name of the secret you want to fetch.
var secretValue = await KeyVaultHelper.GetSecret("mysecret");