I am trying to use DefaultAzureCredential
to connect to a key vault hosted in Azure using the code below:
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration; // Azure.Extensions.AspNetCore.Configuration.Secrets 1.2.2
using Azure.Identity; // Azure.Identity 1.6.0
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
Uri keyVaultUrl = new(builder.Build().GetSection("keyVaultUrl").Value);
DefaultAzureCredentialOptions options = new() { ExcludeEnvironmentCredential = true, ExcludeSharedTokenCredential = true };
builder.AddAzureKeyVault(keyVaultUrl, new DefaultAzureCredential(options));
})
.ConfigurationWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
The code works fine when my web application is published to Azure, and successfully uses the system managed identity I have set up, but when running locally I experience the following exception:
Azure.Identity.AuthenticationFailedException: ‘ManagedIdentityCredential authentication failed. Managed Identity response was not in the expected format. See the inner exception for details.
Status: 403 (GlobalBlock)
and the inner exception reveals:
‘<‘ is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
I understand that managed identities are not expected to work locally but I thought that the point of using DefaultAzureCredential
was to fall back to another credential type instead, as per Microsoft’s documentation. Therefore, I was expecting it to use VisualStudioCredential
instead; in fact, if I explicitly use VisualStudioCredential
then the application does run locally (but not when published to Azure, of course).
I’m at a bit of a loss to explain the behaviour I am seeing and am not sure how to configure DefaultAzureCredential
so that it works both locally and in Azure. Does anybody have any ideas?
I am using Visual Studio 2019 and .NET 5.0.
2
Answers
I encountered the same issue and got it sorted.
Fix was to keep DefaultAzureCredentialOptions enable for desired.
The following credential types if enabled will be tried, in order – EnvironmentCredential, ManagedIdentityCredential, SharedTokenCacheCredential, InteractiveBrowserCredential
Ref: How to use DefaultAzureCredential in both local and hosted Environment (Azure and On-Premise) to access Azure Key Vault?
Do you have the Azure Arc agent installed on your local machine by any chance?
This will create a Managed Server Identity and
DefaultAzureCredential
will try to use that.The agent would be installed in Program FilesAzureConnectedMachineAgent and set these environment variables:
https://learn.microsoft.com/en-us/azure/azure-arc/servers/managed-identity-authentication