74

I am trying to connect my ASP.NET 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 several other .NET framework applications with Azure Keyvault are already using and they are working perfectly.

Looking at my stdout logs I get the following exception every time:

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>
0

14 Answers 14

127

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.

6
  • 6
    Wish I could upvote this more, huge time saver!
    – nurdyguy
    Commented Apr 21, 2022 at 20:44
  • Me too. My VS was using a different Microsoft account in that setting. Would've died of old age before discovering that. Many thanks!
    – NobleGuy
    Commented Feb 11, 2023 at 13:27
  • Gold Star, sir!
    – Jeff Yates
    Commented Jul 6, 2023 at 16:05
  • Yep you were correct! Commented Sep 21, 2023 at 18:19
  • usually you will see a yellow warning sign under your account (in Tools > options > Azure Service Authentication) - but this time it wasnt warning, so I tried to just select "other account" and my already logged in; seems like it was the solution (this time; VS 2022) :D
    – JimiSweden
    Commented Nov 15, 2023 at 14:15
46
Answer recommended by Microsoft Azure Collective

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

10
  • 1
    I had everything except the AZURE_TENANT_ID. After adding it the keyvault worked as expected. Thankyou! Commented Jul 10, 2020 at 9:15
  • where in key vault you added this information?
    – Doof
    Commented Dec 14, 2020 at 13:45
  • 1
    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 Commented Jan 7, 2021 at 10:52
  • Yes, I did the same. It worked for me as well
    – Doof
    Commented Jan 12, 2021 at 12:53
  • 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.
    – E. Moffat
    Commented Mar 18, 2021 at 0:49
12

I followed the below steps to fix the issue. Make sure you have azure portal access and to the required resources.

  1. Install Azure Cli
  2. Open PowerShell as admin
  3. Login to azure using az login command
  4. Open visual studio as administrator
3
  • This worked for me after some of the other solutions didn't do it.
    – Dave
    Commented Jun 20, 2023 at 23:32
  • It worked for me as administrator. I don't understand why it need to be run as administrator, how to allow this flow with standard use of visual studio ?
    – draco951
    Commented Jan 17 at 10:30
  • This one worked for me. i tried every other suggested answer above this. but this worked. Thanks. Commented Mar 10 at 22:30
8

In VS 2019 app, for me, one can re-enter the credentials for the VS logged-in user, which has access to the azure resource group.

8

This means the IDE is unable to find Azure credentials from your build environment/container. If the logout/login method doesn’t work, then from your terminal:

az login

Login with your credentials and re-run the program.

6

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>
4
  • I was having issue with KeyVault connection. It worked after adding the environment variables for Azure ClientID, TenantId and Client Secreat
    – Ratheesh
    Commented Dec 13, 2021 at 7:02
  • How to run the site's application pool identity under your Azure account credentials? Commented Mar 8, 2022 at 6:31
  • I was able to authenticate azure keyvault in localhost but in IIS getting multiple errors on authentication Commented Mar 8, 2022 at 6:32
  • @prasadmaganti You literally enter your email and password you use to login to the Azure Portal in the account credentials.
    – Greg Quinn
    Commented Apr 26, 2022 at 22:12
3

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.

1
  • 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. Commented Apr 7, 2022 at 7:30
1

I was able to resolve this error by installing "Azure CLI Tools" extension and sign-in again through VS Code terminal, please check out more details on this link

0

When debugging a webservice that is hosted in IIS remember to set the application pool Identity to your own account.

I bumped into this out after several hours of trying, the follow code did push me in the the right direction.

        var credential = new DefaultAzureCredential(
            new DefaultAzureCredentialOptions
            {
                VisualStudioTenantId = "xxx",
                ExcludeVisualStudioCodeCredential = true,
                ExcludeEnvironmentCredential = true,
                ExcludeManagedIdentityCredential = true,
                ExcludeVisualStudioCredential = false,
                ExcludeAzureCliCredential = true,
                ExcludeAzurePowerShellCredential = true,
                ExcludeSharedTokenCacheCredential = true
            });
        var token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://database.windows.net/.default" }));

Visual Studio Token provider can't be accessed at c:\windows\system32\inetsrv.IdentityService\AzureServiceAuth\tokenprovider.json

Ofcourse that is the DefaultApplicationPool Identity being system :(

0

For me, it was running fine locally but I experienced this problem with the deployed web app in Azure. It was having trouble accessing KeyVault.

Double check key vault role assignment:

  • Browse to the web app (in portal.azure.com)
  • Click on the Identity menu item on the left
  • Under the System assigned tab, make sure that status is On
  • Then under the Permission section, click Azure role assignments
  • Choose subscription, then select the resource, and "Key Vault Secrets User" or similar as the role, and fill out the rest.

Restart the web app or browse this in App Service Editor console to verify that the problem is resolved. Hope this helps someone!

0

In my situation, Visual Studio logged in to Azure was not enough, though from Microsoft documentation it sounds like an option. I had to install Azure CLI on my Windows 11, and it still did not work to me until I rebooted my Windows

0

I accidentally added a connection string to my azure app service referencing activedirectory, when I needed to use username and pw

0

In my case, I needed to go to C:\Windows\System32\inetsrv\config, open applicationHost.config and set setProfileEnvironment="true" (it was false) on the below line:

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

I tried doing a PoC for this in my .NET app by adding the required variables to appsettings. Of course, that's not the same as adding them to environment variables (d'oh). Here's how I did it:

Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", "ClientId");
Environment.SetEnvironmentVariable( "AZURE_TENANT_ID", "TenantId");
Environment.SetEnvironmentVariable( "AZURE_CLIENT_SECRET", "Secret");

var scope = "api://nameOfApimResource/.default";
var context = new TokenRequestContext(new string[] { scope });
var credential = new EnvironmentCredential();
var token = await cred.GetTokenAsync(credential);

Not the answer you're looking for? Browse other questions tagged or ask your own question.