Issue in accessing Azure Keyvault - DefaultAzureCredential failed to retrieve a token

Viewed 7277

I'm accessing values stored in an Azure Keyvault. Using Visual Studio for my development I'm able to get the data from Keyvault without any issues. However, when the code is deployment to different environments like Test or Stage, I'm getting an error.

The credentials that I'm using to access the Keyvault is stored in the Environment Variables of the project.

Visual Studio > Project > Right-click on Properties > Debug > Environment variables.

The environment variables contain:

  • Azure_Client_Id
  • Azure_Tenant_Id
  • Azure_Client_Secret

The code to access the Keyvault is below and this works fine when used through Visual Studio.

var KeyVaultData = new Azure.Security.KeyVault.Secrets.SecretClient(vaultUri: new Uri(@"https://{VaultName}.vault.azure.net/"), credential: new Azure.Identity.DefaultAzureCredential());

However when this is deployed to other environments, I'm getting the error below:

Exception occured - Azure.Identity.CredentialUnavailableException: DefaultAzureCredential failed to retrieve a token from the included credentials. EnvironmentCredential authentication unavailable. Environment variables are not fully configured. ManagedIdentityCredential authentication unavailable, no managed identity endpoint found. SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.

I don't have access to Azure, but was informed that everything has been setup correctly.

Any help on resolving this is very much appreciated.

EDIT: New code based on the solution given:

const string tenantId = "-----"; 
const string clientId = "-----";
const string clientSecret = "-----";  
var keyvaultCredentials = new ClientSecretCredential(tenantId, clientId, clientSecret); 
var KeyVaultData= new SecretClient(new Uri(@"https://{VaultName}.vault.azure.net/"), keyvaultCredentials);
1 Answers

The DefaultAzureCredential will use environment variables automatically in local, so if you have set the environment variables, of course, it will work. If the environment variables are not available, it will try ManagedIdentityCredential, SharedTokenCacheCredential, InteractiveBrowserCredential, when you deploy your code to the environments you mentioned, they are all not available, so you will get the error.

In this case, if you want to deploy your code to different environments, you need to use ClientSecretCredential, pass the parameters directly to ClientSecretCredential(String, String, String), then the code will work anywhere.

public ClientSecretCredential (string tenantId, string clientId, string clientSecret);
Related