0
votes

I am trying to retrieve a secret from Azure Key Vault (without using credentials, like in this tutorial: example):

public static async Task<string> GetSecret(string secretName)
{
   try
   {
       return (await GetClient().GetSecretAsync(keyVaultUrl, secretName)).Value;
   }
   catch (KeyVaultErrorException)
   {
      return null;
   }
   catch (Exception ex)
   {
      return null;
   }
}

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();
   using KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
   return keyVaultClient;
}

but when I call GetSecret() I get an

object reference not set to an instance of an object

exception.

I am pretty sure that the secret does in fact exist in the key vault.

My key vault url is formatted like "https://my-keyvault.vault.azure.net".

2
You have a using in the GetClient() function. It means the client is disposed before returning it. Put the using in the code where you are using the client, not in the GetClient() function.juunas
@juunas Wow, I'm stupid. Feel free to answer the question so that I can upvote.Eutherpy

2 Answers

2
votes

Because you have a using statement in your GetClient function, the KeyVaultClient is disposed as soon as the function returns. Remove the using there and move it to where you use the client.

private static KeyVaultClient GetClient()
{
   AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
   KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
   return keyVaultClient;
}
public static async Task<string> GetSecret(string secretName)
{
   try
   {
       using var client = GetClient();
       return (await client.GetSecretAsync(keyVaultUrl, secretName)).Value;
   }
   catch (KeyVaultErrorException)
   {
      return null;
   }
   catch (Exception ex)
   {
      return null;
   }
}
1
votes

I test in my site and the code you provided is almost right. Make sure you have login your account in Visual Studio which you create your key vault.

And remove using in code and install nuget.

private static KeyVaultClient GetClient()
{
   AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
   KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
   return keyVaultClient;
}