.net-5azure-keyvaultazure-managed-identitydefaultazurecredential

How to use DefaultAzureCredential in both local and hosted Environment (Azure and On-Premise) to access Azure Key Vault?


We have a web api(.NET 5) which access some secrets from the Azure KeyVault.
In local machine for development, since I am the owner the new vault created, my email has access privilege to keyvault.

Hence I selected my account though VS -->Tools> Options-->Azure Service Authentication-->Account Selection--> "myemail@.com"

I have the below code to fetch secrets from Keyvault and access through configuration like we access the appsettings value.

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
        {
            var appSettings = config.Build();
            var credentialOptions = new DefaultAzureCredentialOptions();
            var credential = new DefaultAzureCredential(credentialOptions);
            config.AddAzureKeyVault(new Uri(appSettings["Url:KeyVault"]), credential);
        })
       .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

We access the secret value like _configuration["secret"] in service and controller layer.

My queries are

1, If I move deploy this code to on premise server how it will work (dev env is on-premise server)?

2, If I deploy this web API to Azure, how to use identity AD App to access the key vault without any code change. We have AD app registered which has read access to this particular Vault.

I want the code to seamlessly work for local and Azure.


Solution

  • DefaultAzureCredential is the new and unified way to connect and retrieve tokens from Azure Active Directory and can be used along with resources that need them

    The DefaultAzureCredential gets the token based on the environment the application is running

    The following credential types if enabled will be tried, in order - EnvironmentCredential, ManagedIdentityCredential, SharedTokenCacheCredential, InteractiveBrowserCredential

    1. IF I move deploy this code to on premise server how it will work (dev env is on-premises server)

    When executing this in a development machine (on-premises server), you need to first configure the environment setting the variables AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_CLIENT_SECRET to the appropriate values for your service principal (app registered in Azure AD)

    1. If I deploy this web app to Azure, how to use identity AD App to access the key vault without any code change. We have AD app registered which have read access to this Vault

    You can enable System assigned Managed Identity for your web app. Add access policy for this identity in your Azure Key Vault to read the secrets. Now without making any changes in your code, your web app would be able to read the key vault secrets