Azure KeyVault: Azure.Identity.CredentialUnavailableException: DefaultAzureCredential failed to retrieve a token from the included credentials

33,469

Solution 1

Could you validate that you are setting the following system environment variables?

AZURE_CLIENT_ID - service principal's app id

AZURE_TENANT_ID - id of the principal's Azure Active Directory tenant

AZURE_CLIENT_SECRET - one of the service principal's client secrets

Solution 2

This error can also occur if Visual Studio loses it's Azure Service Authentication connection for some reason or your actual AD credentials have changed (for example a password change).

In this case, simply signing in again has fixed this for me:

In Visual Studio, go to Tools > Options. Expand "Azure Service Authentication" > "Account Selection." If you see a "Reenter your credentials" link, click it and sign in again. If not, try a regular sign-out + sign-in via your Visual Studio profile in the top right.

Solution 3

I have also faced this issue in VS 2019 app. Just re-enter the credentials for VS logged-in user, which have access on azure resource group.

I hope it will fix the issue.

Solution 4

If you're running your site locally using IIS, and not IIS Express, you may need to run the site's application pool identity under your Azure account credentials, so the exact credentials you use to login in your browser to portal.azure.com or dev.azure.com. Your PAT will not work.

Once that has been setup, recycle the app pool.

Then go to %windir%\System32\inetsrv\config\applicationHost.config

Search for "setProfileEnvironment". If it's set to "false", change it to "true".

If not present, add it under applicationPoolDefaults tag i.e

<applicationPoolDefaults managedRuntimeVersion="v4.0">
    <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</applicationPoolDefaults>

Solution 5

For me this was just the first exception, drilling down further (Continue => Continue => Continue) I eventually got to the REAL exception:

''az' is not recognized as an internal or external command'

Turns out I had forgotten to install Azure CLI on my machine!

Once I did that I still got the original 'CredentialUnavailableException' but its handled (not sure why my debugger is breaking on it, but that's another story) and everything worked.

This StackOverflow link helped.

Share:
33,469

Related videos on Youtube

Dylan Meivis
Author by

Dylan Meivis

Hi there

Updated on February 18, 2022

Comments

  • Dylan Meivis
    Dylan Meivis about 2 years

    I am trying to connect my aspnet core application that is targeting .net framework with Azure Keyvault. On a new azure vm that supports identity everything works fine, but this application is hosted on a classic azure vm that does not support identity. I made the system environment variable AzureServiceAuthConnectionString which severable other .net framework applications with Azure keyvault are already using and are working perfectly.

    Looking at my stdout logs I get the following exception everytime.

    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, the requested identity has not been assigned to this resource.
    

    I use the following code in the startup:

            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)               
           .UseApplicationInsights(ConfigurationManager.AppSettings["applicationInsightsInstrumentationKey"])
                    .ConfigureKestrel(options => options.AddServerHeader = false)
                    .UseIISIntegration()
                    .ConfigureAppConfiguration((context, config) =>
                    {
                        var vaultName = ConfigurationManager.AppSettings["VaultName"];
                        if (!string.IsNullOrEmpty(vaultName))
                        {
                            var azureServiceTokenProvider = new AzureServiceTokenProvider();
                            var keyVaultClient = new KeyVaultClient(
                                new KeyVaultClient.AuthenticationCallback(
                                    azureServiceTokenProvider.KeyVaultTokenCallback));
    
                            config.AddAzureKeyVault(
                                $"https://{vaultName}.vault.azure.net/",
                                keyVaultClient,
                                new DefaultKeyVaultSecretManager());
                        }
                    })
                    .UseStartup<Startup>();
    

    And in the web.config the following items :

       <configSections>
          <section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false"/>
       </configSections>
       <configBuilders>
        <builders>
          <add name="AzureKeyVault" vaultName="<#= this.VaultName #>" type="Microsoft.Configuration.ConfigurationBuilders.AzureKeyVaultConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Azure, Version=2.0.0.0, Culture=neutral" vaultUri="https://<#= this.VaultName #>.vault.azure.net" />
        </builders>
      </configBuilders>
      <connectionStrings configBuilders="AzureKeyVault">
          <add name="ConnectionString" connectionString="" providerName="System.Data.SqlClient"/>
      </connectionStrings>
    
  • Dylan Meivis
    Dylan Meivis almost 4 years
    I had everything except the AZURE_TENANT_ID. After adding it the keyvault worked as expected. Thankyou!
  • Code run
    Code run over 3 years
    where in key vault you added this information?
  • Dylan Meivis
    Dylan Meivis over 3 years
    Sorry for the late response! The 3 lines of information you see above I added them into my environment variables on the virtual machine my application runs on. @Coderun
  • Code run
    Code run over 3 years
    Yes, I did the same. It worked for me as well
  • E. Moffat
    E. Moffat about 3 years
    The key here for me was "system" environment variables. I tried setting them in code at the process level and it didn't work that way. Setting them from the system dialog worked.
  • CredibleAshok
    CredibleAshok almost 3 years
    But this only works, when I login in Visual Studio. If I keep just these environment variables and do not sign in, it doesn't work.
  • user510101
    user510101 over 2 years
    I'm having similar issues but at build time in Azure DevOps Build Pipeline. When the VSBuild task runs, and it gets into the MvcBuildViews portion of the MSBuild, it encounters an error: ##[error]ASPNETCOMPILER(0,0): Error ASPRUNTIME: Type is not resolved for member 'Azure.Identity.CredentialUnavailableException,Azure.Identit‌​y, Version=1.4.1.0, Culture=neutral, PublicKeyToken=92742159e12e44c8'. I've added an Azure CLI task in the pipeline, before the build, so there's an active az login using the service connection. I can also confirm the service connection can enumerate kv secrets.
  • Ratheesh
    Ratheesh over 2 years
    I was having issue with KeyVault connection. It worked after adding the environment variables for Azure ClientID, TenantId and Client Secreat
  • prasad maganti
    prasad maganti about 2 years
    How to run the site's application pool identity under your Azure account credentials?
  • prasad maganti
    prasad maganti about 2 years
    I was able to authenticate azure keyvault in localhost but in IIS getting multiple errors on authentication
  • Laurent Greyling
    Laurent Greyling about 2 years
    Thanks, this should be the first thing people should try. This was also my issue. Just one thing, after installing Azure CLI close VS and reopen it. Else you still get the error.
  • nurdyguy
    nurdyguy about 2 years
    Wish I could upvote this more, huge time saver!
  • Greg Quinn
    Greg Quinn about 2 years
    @prasadmaganti You literally enter your email and password you use to login to the Azure Portal in the account credentials.