'Azure function can access Key Vault when run locally in visual Studio but not when run on the portal

I am reading values from a key vault in an azure function. When running locally it works. After deploying and running from the portal it give the error.

This is how i am getting the data from key vault:

    var vaultUrl = Environment.GetEnvironmentVariable("KV_URL");
    var client = new SecretClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

    KeyVaultSecret graphSecret = client.GetSecret("val1");
    KeyVaultSecret tenantId = client.GetSecret("val2");
    KeyVaultSecret clientId = client.GetSecret("val3");

I have created a system assigned identity for the function in the portal and granted it read and list rights on the key vault secrets.

I dont have any logging set up in the function, which could possibly give more information. Is application insights the only way to gather information from the function as it runs?



Solution 1:[1]

Here the Key Vault URL is defined in the local.settings.json so that you're getting that using Environment.GetEnvironmentVariable locally.

When running in the Azure Portal, you have to store this Key Vault URI in the Azure Function App > Configuration > Application settings, then the same code works in Azure also.

enter image description here

Refer here for a practical workaround.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HariKrishnaRajoli-MT