coder
coder

Reputation: 4313

How to Read Azure KeyVault Secret in Asp.Net Core Web Api hosted on Azure VM IIS

The code below works on my local machine passing DefaultAzureCredential(). But when I host it on IIS on Azure VM, the authentication fails. I tried setting the ApplicationPool's identity to my credential since I have access to the Azure KeyVault, still the same 403 forbidden error. Deploying as AppServices on Azure is not an option currently.

What is the best way to read Azure KeyVault Secrets in this scenario?

string kvUri = "https://mykeyvault.vault.azure.net/";
string secretName = "MyConnectionString";

var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
var secret = await client.GetSecretAsync(secretName);
Console.WriteLine(secret?.Value?.Value);

Upvotes: 0

Views: 865

Answers (1)

Harshitha
Harshitha

Reputation: 7392

still the same 403 forbidden error

We need to enable the system-assigned Managed Identity on the VM which we have deployed our Web App.

enter image description here

  • And provide the permissions for the Identity which you have set in previous step.Run the below command in Azure CLI
az keyvault set-policy --name 'KeyVaultName' --object-id "ObjectID of SystemAssigned Managed Identity" --secret-permissions  get list set delete

Make sure you have given access permissions to retrieve the Key Vault.

In Azure Keyvault => Access policies , select the Get,List permissions and provide the Principal - name will be same as your deployed WebApp , continue with the steps and Review +create

enter image description here

Upvotes: 1

Related Questions