Search code examples
.netvisual-studioazure-keyvaultconnected-services

How to properly store and extract AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET?


I have this azure key vault in which I have stored an api key. I have via Visual studio added the azure key vault as an connected service to the project.

I try to get my keyvalue stored in akv via this code

    HttpClient client = new HttpClient();
    string keyVaultName = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("web-kv")) ? Environment.GetEnvironmentVariable("web-kv") : throw new ArgumentNullException("web-kv");
    string kvUri = "https://" + keyVaultName + ".vault.azure.net";
    bool success = Uri.TryCreate(kvUri, UriKind.Absolute, out Uri uri);
    if(!success)
    {
        throw new Exception(kvUri);
    }
        var akvClient = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
        var apiKey = akvClient.GetSecret("LicenseApiKey");

Which returns this exception

Azure.Identity.AuthenticationFailedException: The DefaultAzureCredential failed to retrieve a token from the included credentials.
  EnvironmentCredential is unavailable Environment variables not fully configured. AZURE_TENANT_ID and AZURE_CLIENT_ID must be set, along with either AZURE_CLIENT_SECRET or AZURE_USERNAME and AZURE_PASSWORD. Currently set variables [  ].
  ManagedIdentityCredential is unavailable No managed identity endpoint found..
  SharedTokenCacheCredential is unavailable No accounts were discovered in the shared token cache. To fix, authenticate through tooling supporting azure developer sign on..

the application is not registerd as an APP in azure, and for some reason it does not detect that the environment variable is set?


Solution

  • I ended up using an approach where I let the Azure pipeline insert the secrets into my appSetting when I am deploying, hence the code will not be interfacing with the keyvault.