Search code examples
c#azureasp.net-core-webapiazure-keyvaultazure-identity

From localhost C# Web API - Accessing secret from Azure KeyVault throws error Invalid Issuer


I am trying from my local web api, to retrieve secret from KeyVault using Azure.Identity lib. but it throws Invalid Issuer. Giving below the code I am using

My current code

var client = new SecretClient(new Uri("key-vault-url"), new DefaultAzureCredential());    ==> line #1
var secret = client.GetSecret("DicomSecret").Value;                           ==> line #2

As soon as it parses line#2 it throws the below error. enter image description here

What I have tried

  1. I have added my Azure credential in the KeyVault thru' Add Access Policy
  2. Tried using ManagedIdentityCredential instead of DefaultAzureCredential in line#1
  3. Also tried using VisualStudioCredential instead of DefaultAzureCredential in line#1

I also read that I can be using EnvironmentCredential for which I need to provide AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET but I am not exactly sure how to and what to include for this - I do not have access to AAD.

Please let me know how to resolve this issue.


Solution

  • Since I was trying to connect to Azure from my local development environment (VS 2019) it was expecting additional credentials.

    So from my dev environment (localhost) I had to use DefaultAzureCredentialOptions VisualStudioTenantId along with SecretClient.

    var tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions()
     { 
         VisualStudioTenantId = tenantId, 
         SharedTokenCacheTenantId = tenantId 
    };
    var client = new SecretClient(
                 new Uri(key-vault-url), 
                 new DefaultAzureCredential(options)
                 );
      
    

    The above helped me to execute from my local but after deploying it to Azure Ap Service the below line of code was sufficient. So I used the above code only for my local testing.

    var client = new SecretClient(new Uri("key-vault-url"), new DefaultAzureCredential());