Reputation: 370
I got the Azure Key Vault working with my web app using MSI. Now I'm in the process of setting up the KV for my webjobs, which are just console applications running .Net Framework 4.7.2. When I try to include "Secure with Azure Key Vault" as a connected service, it doesn't show up on the list. I'm running the latest version of Visual Studio 2019 Professional. I've updated and even reinstalled VS, but it still doesn't show. Are console applications just not allowed to have Key Vaults?
How would a web job work with Key Vault using MSI?
Upvotes: 1
Views: 2843
Reputation: 12153
Of course you can use Azure web app MSI to access your key vault in Azure console app webjobs. I implemented a simple console app webjobs demo which reads a secret from key vault for you , try the code below :
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kvtest
{
class Program
{
static void Main(string[] args)
{
var keyVaultName = "<your key vault name>";
var secretName = "<your secret name>";
Console.WriteLine("Get " + secretName + " from key vault :" + GetSecret(secretName, keyVaultName).GetAwaiter().GetResult());
}
public static async Task<string> GetSecret(string secretName,string keyVaultName)
{
try
{
return (await GetClient().GetSecretAsync("https://"+ keyVaultName + ".vault.azure.net/", secretName)).Value;
}
catch (Exception ex)
{
return ex.Message;
}
}
public static async Task<string> GetAccessTokenAsync()
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
return await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
}
private static KeyVaultClient GetClient()
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
return keyVaultClient;
}
}
}
Publish to Azure webapp and run it manually, check its log , we can see the it has got secret value from Key vault successfully :
Btw, before run this demo, pls make sure that you have enabled MSI for your Azure webapp and you have configed access policy in your Azure key vault for it.
If you have any further concerns , pls feel free to let me know .
Upvotes: 4