Home > Net >  Azure KeyVault is giving a null reference exception when running GetSecret()
Azure KeyVault is giving a null reference exception when running GetSecret()

Time:05-27

When I try to get the API secret from Azure KeyVault, I am receiving a null reference error. I have the Key set up in the KeyVault, but secret is coming back as null.

    public static string GetKeyInformation(API_KEY)
    {
        if (string.IsNullOrEmpty(API_KEY))
        {
            var keyVaultUrl = "https://socialflutter.vault.azure.net/";

            var credential = new DefaultAzureCredential();

            var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential);

            KeyVaultSecret secret = client.GetSecret();

            Console.WriteLine($"{secret.Name}: {secret.Value}");

            API_KEY = secret.Value;
        }

        return API_KEY;
    }

Any help is greatly appreciated.

CodePudding user response:

The null reference error is happening because of the following line: KeyVaultSecret secret = client.GetSecret();

Even if you just have a single secret defined, Azure KeyVault will not know how to read the Key.

You will want the following syntax: KeyVaultSecret secret = client.GetSecret(<KEY_NAME>);

To find the <KEY_NAME>, refer to the screenshot below:

  1. Go to Key Vault
  2. Click on Secrets
  3. Copy the Name of the Secret

Azure KeyVault

  • Related