azure-sdk-for-net: DefaultAzureCredential fails when multiple accounts are available and defaulting to SharedTokenCacheCredential
Describe the bug
I am using v1.0 of Azure.Identity on both .NET Framework and .NET Core and am attempting to connect to a blob container via DefaultAzureCredential:
async static Task CreateBlockBlobAsync(string accountName, string containerName)
{
// Construct the blob container endpoint from the arguments.
string containerEndpoint = string.Format("https://{0}.blob.core.windows.net/{1}", accountName, containerName);
// Get a credential and create a client object for the blob container.
var containerClient = new BlobContainerClient(new Uri(containerEndpoint), new DefaultAzureCredential());
// Create the container if it does not exist.
await containerClient.CreateIfNotExistsAsync();
}
I am logged into Visual Studio with two accounts. When I run this, I get the following:
Azure.Identity.AuthenticationFailedException
HResult=0x80131500
Message=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 Multiple accounts were discovered in the shared token cache. To fix, set the AZURE_USERNAME environment variable to the preferred username, or specify it when constructing SharedTokenCacheCredential.
Discovered Accounts: [ '****@outlook.com', '****@microsoft.com' ].
See inner exception for more detail.
Source=Azure.Identity
StackTrace:
at Azure.Identity.DefaultAzureCredential.<GetTokenAsync>d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Identity.DefaultAzureCredential.<GetTokenAsync>d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.<ProcessAsync>d__8.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>d__1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Azure.Core.Pipeline.RetryPolicy.<ProcessAsync>d__11.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Azure.Core.Pipeline.RetryPolicy.<ProcessAsync>d__11.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>d__1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>d__1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobRestClient.Container.<CreateAsync>d__0.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobContainerClient.<CreateInternal>d__36.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobContainerClient.<CreateIfNotExistsInternal>d__35.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobContainerClient.<CreateIfNotExistsAsync>d__34.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at StorageAccountSample.Program.<CreateBlockBlobAsync>d__1.MoveNext() in C:\Users\tasou\source\repos\StorageAccountSample\StorageAccountSample\Program.cs:line 24
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at StorageAccountSample.Program.<Main>d__0.MoveNext() in C:\Users\tasou\source\repos\StorageAccountSample\StorageAccountSample\Program.cs:line 12
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at StorageAccountSample.Program.<Main>(String[] args)
Inner Exception 1:
AggregateException: The DefaultAzureCredential failed to retrieve a token from the included credentials.
Inner Exception 2:
CredentialUnavailableException: 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 [ ]
At this, point, I attempt to set AZURE_USERNAME. This fails with the following:
Azure.Identity.AuthenticationFailedException
HResult=0x80131500
Message=The DefaultAzureCredential failed due to an unhandled exception: SharedTokenCacheCredential failed with unhandled exception The authentication request failed due to an unhandled exception. See inner exception for details..
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 [ AZURE_USERNAME ].
ManagedIdentityCredential is unavailable No managed identity endpoint found..
SharedTokenCacheCredential failed with The authentication request failed due to an unhandled exception. See inner exception for details..
See inner exception for more detail.
Source=Azure.Identity
StackTrace:
at Azure.Identity.DefaultAzureCredential.<GetTokenAsync>d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Identity.DefaultAzureCredential.<GetTokenAsync>d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.<ProcessAsync>d__8.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>d__1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Azure.Core.Pipeline.RetryPolicy.<ProcessAsync>d__11.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Azure.Core.Pipeline.RetryPolicy.<ProcessAsync>d__11.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>d__1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>d__1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobRestClient.Container.<CreateAsync>d__0.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobContainerClient.<CreateInternal>d__36.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobContainerClient.<CreateIfNotExistsInternal>d__35.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Azure.Storage.Blobs.BlobContainerClient.<CreateIfNotExistsAsync>d__34.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at StorageAccountSample.Program.<CreateBlockBlobAsync>d__1.MoveNext() in C:\Users\tasou\source\repos\StorageAccountSample\StorageAccountSample\Program.cs:line 25
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at StorageAccountSample.Program.<Main>d__0.MoveNext() in C:\Users\tasou\source\repos\StorageAccountSample\StorageAccountSample\Program.cs:line 13
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at StorageAccountSample.Program.<Main>(String[] args)
Inner Exception 1:
AggregateException: The DefaultAzureCredential failed due to an unhandled exception: SharedTokenCacheCredential failed with unhandled exception The authentication request failed due to an unhandled exception. See inner exception for details..
Inner Exception 2:
CredentialUnavailableException: 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 [ AZURE_USERNAME ]
It appears that when multiple accounts are available, SharedTokenCacheCredential expected AZURE_USERNAME to disambiguate. However, since EnvironmentCredential runs first, it reports an error.
How can I use DefaultCredential when using multiple accounts in VS? I would expected Tools->Options->Azure Service Authentication->Account Selection in VS would be honored but it does not seem to be (which works with Microsoft.Azure.Services.AppAuthentication.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 8
- Comments: 42 (9 by maintainers)
I’m running in Visual Studio Code and am just authenticated via the command line using
az login. When I runaz account listis it lists multiple accounts, but one account is set to"isDefault": true. DefaultAzureCredential does not seem to be respecting that flag, so this seems to be broken whether you are using Visual Studio or not.Please fix! This unnecessarily complicates the local development environment.
Update to my issue above
I created new user in Azure AD and used that to log in. This user is separate from that I used to create/login to the Azure Subscription. It works fine with the new user.
FWIW, I have written out the different options I used to get DefaultAzureCredential work on my local machine here
With inspiration from @xperiandri… what solved the issue for me was to configure AZURE_USERNAME and AZURE_TENANT_ID in VS2019 enterprise. In my case the issue was related to running an azure function locally. I added the above environment variables in (right click) [yourproject] --> properties --> debug - under section “Environment Variables”.
Above there has been some discussions which version to use of the Azure.Identity library. For me this is working with version 1.3.0 (Latest stable version at the time of writing)
I didn’t have to configure the DefaultAzureCredentialOptions - I just used the default constructor - DefaultAzureCredential()
My method that caused all the trouble - but now working well both locally and being deployed to azure: public static async Task<string> getSecretFromKeyvault(string _keyvaultName, string _secretName) { var kvUri = “https://” + _keyvaultName + “.vault.azure.net”; var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential()); var secret = await client.GetSecretAsync(_secretName); return secret.Value.Value; }
In my case, my
AZURE_USERNAMEwas not an email address, though this isn’t indicated anywhere in Visual Studio and is tricky to find. Go to your Azure portal -> Azure Active Directory -> Users -> <your user> -> Profile (the default selection), and look at “Name” in the Identity section.Ok, when I do this, I get the following:
This occurs a number of times it seems. I had to click “don’t break on this” to be able to get through it.
I faced problems with
DefaultAzureCredentialwith a single account.I was able to over come this problem with a different type of Credential:
ClientSecretCredentialpom.xml
Hi all, This issue has arose again in “Azure.Identity” Version=“1.3.0”. Everething works well in “Azure.Identity” Version=“1.2.0”.
I was experiencing the same issues. Moved to Azure.Identity 1.2.0-preview.3 and everything works fine debugging from Visual Studio with multiple accounts and an account selected in Azure Service Authentication
I solved this problem by just setting the environment variable named “AZURE_USERNAME” = [your azure account email id] that you want to use for the authentication in development mode.
How to Setup Environment Variable? for (Window 10) Window Key >> Search >> ENV >>open environment variable editor
assume you mean AZURE_USERNAME not AZURE_NAME.
Hi @spmanjunath , I was unable to resolve this. I worked around this issue by using a different way to connect to the Key Vault:
https://docs.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-3.1
This worked instantly, you will need list permissions on secrets obviously, and it will retrieve ALL secrets and not only the ones requested. But at least it was working as expected…
Worth a check it isn’t this issue when using AZURE_USERNAME. The upper/lower case of the email account has to match the account that was registered in VS. https://github.com/Azure/azure-sdk-for-net/issues/10816. @schaabs has put a fix in.
Thanks @MikePennington, https://github.com/Azure/azure-sdk-for-net/pull/11575
I am getting the same error. Tried clearing the ‘%LOCALAPPDATA%/.IdentityService’ cache and logged back into VS with just one account. Below is what I see
at Microsoft.Identity.Client.ApiConfig.Executors.ClientApplicationBaseExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenSilentParameters silentParameters, CancellationToken cancellationToken) at Azure.Identity.MsalPublicClient.AcquireTokenSilentAsync(String[] scopes, IAccount account, CancellationToken cancellationToken) at Azure.Identity.SharedTokenCacheCredential.GetTokenImplAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) ErrorCode: invalid_client StatusCode: 401Happy to provide any other details
I’m using VS Professional version so not sure if that matters but I don’t see the
Apply Filterbutton next to the account. 😞