Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DefaultAzureCredential fails when multiple accounts are available and defaulting to SharedTokenCacheCredential #8658

Closed
twsouthwick opened this issue Nov 6, 2019 · 42 comments
Assignees
Labels
Azure.Identity Client This issue points to a problem in the data-plane of the library.

Comments

@twsouthwick
Copy link

twsouthwick commented Nov 6, 2019

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.

@triage-new-issues triage-new-issues bot added the needs-triage Workflow: This is a new issue that needs to be triaged to the appropriate team. label Nov 6, 2019
@pakrym
Copy link
Contributor

pakrym commented Nov 6, 2019

cc @schaabs

@pakrym pakrym added Azure.Identity Client This issue points to a problem in the data-plane of the library. labels Nov 6, 2019
@triage-new-issues triage-new-issues bot removed the needs-triage Workflow: This is a new issue that needs to be triaged to the appropriate team. label Nov 6, 2019
@schaabs
Copy link
Member

schaabs commented Nov 6, 2019

@twsouthwick Thanks for reporting this issue. It seems that the error message you're getting here is a pretty confusing. The CredentialUnavailableException is actually handled by the DefaultAzureCredential and is basically used as a signal to try the next credential in the chain. It looks like the SharedTokenCacheCredential is actually attempting to authenticate in the second error you shared, but this failed with an unhandled exception.

 SharedTokenCacheCredential failed with unhandled exception The authentication request failed due to an unhandled exception.  See inner exception for details..

So I believe in this case AZURE_USERNAME is properly being used to disambiguate, but when we tried to authenticate with this account an exception was raised. Unfortunately the specific exception which caused the SharedTokenCacheCredential to fail in this case isn't being added to the exception message, and is not intuitive to dig out as it's actually buried in the tree of inner exceptions. To dig out this exception message and callstack you'd need to print the whole tree of inner exceptions. I've created issue #8665 to address this.

As to your second point. We are working to get parity with Microsoft.Azure.Services.AppAuthentication. We are using a newer mechanism to share credentials between VS and the running application, which currently doesn't honor the selection in Tools->Options->Azure Service Authentication->Account Selection. For the time being AZURE_USERNAME needs to be specified to differentiate.

@twsouthwick
Copy link
Author

That makes sense. Let me know if there's any debugging I can do on my side

@pakrym
Copy link
Contributor

pakrym commented Nov 7, 2019

Can you enable Break on all exceptions (https://docs.microsoft.com/en-us/visualstudio/debugger/managing-exceptions-with-the-debugger?view=vs-2019) are copy the exception details for the exception that gets thrown in Microsoft.Identity.Client

@twsouthwick
Copy link
Author

Ok, when I do this, I get the following:

Microsoft.Identity.Client.MsalServiceException
  HResult=0x80131500
  Message=AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.
Trace ID: ab88f102-5946-4b60-ac06-294565df0100
Correlation ID: 61d55a29-6ef5-4caf-ba0b-01ad1cbd8dea
Timestamp: 2019-11-07 23:13:55Z
  Source=Microsoft.Identity.Client
  StackTrace:
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateErrorResponse(HttpResponse response, RequestContext requestContext)

This occurs a number of times it seems. I had to click "don't break on this" to be able to get through it.

@jackfoxy
Copy link

Our team is also suffering from what I think is this problem, although a somewhat different call stack.
Please fix this.

@tuanle07
Copy link

tuanle07 commented Mar 6, 2020

Had exactly the same issue as well when I logged into VS with 2 accounts (though I selected only 1 account for Azure default credentials). Please fix it!

@arkiaconsulting
Copy link

@tuanle07 Please make sure that the only remaining account has not been invited in another tenant(s). If this is the case, in the VS Account UI, untick all tenants except the one that you're interested in.

@tuanle07
Copy link

tuanle07 commented Mar 7, 2020

@tuanle07 Please make sure that the only remaining account has not been invited in another tenant(s). If this is the case, in the VS Account UI, untick all tenants except the one that you're interested in.

Where do you see the list of tenants in the VS Account Settings UI? I can only see a list of logged in accounts and ability to remove them. 🤔

@arkiaconsulting
Copy link

In the account window, click on the Apply filter next to the account you're interested in.

image

If you don't have this option, your account may not be invited in other tenants, and as such, my solution does not apply to your case...

@tuanle07
Copy link

tuanle07 commented Mar 7, 2020

In the account window, click on the Apply filter next to the account you're interested in.

image

If you don't have this option, your account may not be invited in other tenants, and as such, my solution does not apply to your case...

I’m using VS Professional version so not sure if that matters but I don’t see the Apply Filter button next to the account. 😞

@alex-zyl
Copy link

Also getting the error while having multiple accounts in VS:

SharedTokenCacheCredential authentication unavailable. Multiple accounts were found in the cache. Use username and tenant id to disambiguate.

@rahulpnath
Copy link

Ok, when I do this, I get the following:

Microsoft.Identity.Client.MsalServiceException
  HResult=0x80131500
  Message=AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.
Trace ID: ab88f102-5946-4b60-ac06-294565df0100
Correlation ID: 61d55a29-6ef5-4caf-ba0b-01ad1cbd8dea
Timestamp: 2019-11-07 23:13:55Z
  Source=Microsoft.Identity.Client
  StackTrace:
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateErrorResponse(HttpResponse response, RequestContext requestContext)

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 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: 401

Happy to provide any other details

@rahulpnath
Copy link

rahulpnath commented Mar 21, 2020

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

@jrsurya
Copy link

jrsurya commented Apr 17, 2020

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

@MikePennington
Copy link

MikePennington commented Apr 21, 2020

I'm running in Visual Studio Code and am just authenticated via the command line using az login. When I run az account list is 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.

@AlexanderSher
Copy link
Contributor

Hi @MikePennington ,

When client is authenticated using Azure CLI, its account is extracted using Azure CLI az account get-access-token command as well, and that command should` respect that flag: https://github.com/Azure/azure-cli/blob/b38e150c5d41f80859b329612f8cd70c9d1efc2a/src/azure-cli-core/azure/cli/core/_profile.py#L506

Do you have an issue that DefaultAzureCredential authenticates you with wrong account or it doesn't authenticate at all?

@MikePennington
Copy link

MikePennington commented Apr 22, 2020

@AlexanderSher, DefaultAzureCredential is not authenticating me at all. I am getting a similar error to the one provided by the OP:

"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. Multiple accounts were found in the cache. Use username and tenant id to disambiguate."

@schaabs
Copy link
Member

schaabs commented Apr 22, 2020

@MikePennington what version of Azure.Identity are you currently using? Support for authentication through the Azure CLI was only recently added in 1.2.0-preview.1 and we have yet to GA this feature. Based off the error message you shared it seems that you're using an older version which doesn't have this support.

@MikePennington
Copy link

@schaabs, thanks for the info, I was using the latest non-preview release, 1.1.1.

I tried the 1.2.0-preview.2, and it failed with the following error:

System.Private.CoreLib: Exception while executing function: List. Azure.Identity: DefaultAzureCredential authentication failed. Azure.Identity: VisualStudioCredential authentication failed. System.Text.Json: 'D' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.

So then I reverted to 1.2.0-preview.1, and it worked! So it seems like something seems to have gone sideways between 1.2.0-preview.1 and 1.2.0-preview.2.

@AlexanderSher
Copy link
Contributor

@MikePennington , can you please add a call stack from the bug that you have on 1.2.0-preview.2?

@MikePennington
Copy link

@AlexanderSher

Could not download blob from storage account.
Azure.Identity: DefaultAzureCredential authentication failed. Azure.Identity: VisualStudioCredential authentication failed. System.Text.Json: 'D' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.

Azure.Identity.AuthenticationFailedException: DefaultAzureCredential authentication failed.
 ---> Azure.Identity.AuthenticationFailedException: VisualStudioCredential authentication failed.
 ---> System.Text.Json.JsonReaderException: 'D' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
   at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.JsonDocument.Parse(ReadOnlySpan`1 utf8JsonSpan, Utf8JsonReader reader, MetadataDb& database, StackRowStack& stack)
   at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 utf8Json, JsonReaderOptions readerOptions, Byte[] extraRentedBytes)
   at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 json, JsonDocumentOptions options)
   at System.Text.Json.JsonDocument.Parse(String json, JsonDocumentOptions options)
   at Azure.Identity.VisualStudioCredential.RunProcessesAsync(List`1 processStartInfos, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.VisualStudioCredential.RunProcessesAsync(List`1 processStartInfos, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.VisualStudioCredential.GetTokenImplAsync(TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Azure.Identity.VisualStudioCredential.GetTokenImplAsync(TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.VisualStudioCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Identity.DefaultAzureCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Storage.Blobs.BlobRestClient.Blob.DownloadAsync(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri resourceUri, String version, String snapshot, Nullable`1 timeout, String range, String leaseId, Nullable`1 rangeGetContentHash, Nullable`1 rangeGetContentCRC64, String encryptionKey, String encryptionKeySha256, Nullable`1 encryptionAlgorithm, Nullable`1 ifModifiedSince, Nullable`1
ifUnmodifiedSince, Nullable`1 ifMatch, Nullable`1 ifNoneMatch, String requestId, Boolean async, String operationName, CancellationToken cancellationToken)
   at Azure.Storage.Blobs.Specialized.BlobBaseClient.StartDownloadAsync(HttpRange range, BlobRequestConditions conditions, Boolean rangeGetContentHash, Int64 startOffset, Boolean async, CancellationToken cancellationToken)
   at Azure.Storage.Blobs.Specialized.BlobBaseClient.DownloadInternal(HttpRange range, BlobRequestConditions conditions, Boolean rangeGetContentHash, Boolean async, CancellationToken cancellationToken)
   at Azure.Storage.Blobs.Specialized.BlobBaseClient.DownloadAsync(HttpRange range, BlobRequestConditions conditions, Boolean rangeGetContentHash, CancellationToken cancellationToken)
   at Azure.Storage.Blobs.Specialized.BlobBaseClient.DownloadAsync(CancellationToken cancellationToken)
   at Azure.Storage.Blobs.Specialized.BlobBaseClient.DownloadAsync()
   at DecilesApi.Repos.DecilesRepo.DownloadBlobAsync(String accountName, String containerName, String blobName) in C:\Users\ez9wv1i\source\repos\Application\Service.Deciles\src\DecilesApi\Repos\DecilesRepo.cs:line 115

@AlexanderSher
Copy link
Contributor

AlexanderSher commented Apr 24, 2020

Thanks @MikePennington, #11575

@cineas
Copy link

cineas commented Apr 25, 2020

Thanks, using Azure.Identity 1.2.0-preview.1, and it worked

@rightincode
Copy link

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

@TomMalow
Copy link

I am experiencing authentication issues with multiple accounts even when using 1.2.0-preview.3
{"error":{"code":"Unauthorized","message":"AKV10032: Invalid issuer. Expected one of https://sts.windows.net/<TenantId1>/, https://sts.windows.net/<TenantId2>/, https://sts.windows.net/<TenantId3>/, found https://sts.windows.net/<TenantId4>/."}}

I have two different accounts added to Visual Studio, but the same account is always used regardless of which account is selected in Azure Service Authentication or defined in AZURE_USERNAME. Logging out all accounts and only adding the desired account resolves the problem. The problematic account is also the account that is logged into windows so it seems like it prioritize that first.

@alhardy
Copy link

alhardy commented Jun 3, 2020

Experience similar issues authenticating to azure app configuration using DefaultAzureCredential.

"MsalServiceException: A configuration issue is preventing authentication - check the error message from the server for details.You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details. Original exception: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908."

I've tried both the latest stable and preview versions of Azure.Identity.

            var credentials = Environments.IsDevelopment
                ? new DefaultAzureCredential()
                : (TokenCredential)new ManagedIdentityCredential();

            builder.AddAzureAppConfiguration(
                options =>
                {
                    options.Connect(new Uri(appConfigEndpoint), credentials);
                    options.ConfigureKeyVault(kv => kv.SetCredential(credentials));
                });

I'm authenticated via both visual studio and az cli, only authenticated to a single azure subscription.

My user has data reader access to azure app configuration and also access to the keyvault connected.

Same code works if I replace DefaultAzureCredential with InteractiveBrowserCredential

@AlexanderSher
Copy link
Contributor

@alhardy, can you please post a full call stack?

@Rolorob
Copy link

Rolorob commented Jun 9, 2020

I'm having exactly the same issue as alhardy. Not sure what is going wrong.
But I do have the full calls tack:

Azure.Identity.AuthenticationFailedException
  HResult=0x80131500
  Message=DefaultAzureCredential authentication failed.
  Source=Azure.Identity
  StackTrace:
   at Azure.Identity.DefaultAzureCredential.<GetTokenImplAsync>d__11.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
   at Azure.Identity.DefaultAzureCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.<AuthenticateRequestAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.<ProcessCoreAsync>d__8.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   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.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
   at Azure.Core.Pipeline.RetryPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipeline.Send(HttpMessage message, CancellationToken cancellationToken)
   at Azure.Core.Pipeline.HttpPipeline.SendRequest(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest[TResult](RequestMethod method, Func`1 resultFactory, CancellationToken cancellationToken, String[] path)
   at Azure.Security.KeyVault.Secrets.SecretClient.GetSecret(String name, String version, CancellationToken cancellationToken)
   at BestelBoer.Registrations.Registrations.GetSecret(SecretClient client, String key) in C:\git\bestelboer\BackendWebsite\BestelBoer.Registrations\Registrations.cs:line 106

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
AuthenticationFailedException: SharedTokenCacheCredential authentication failed.

Inner Exception 2:
MsalServiceException: A configuration issue is preventing authentication - check the error message from the server for details.You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details.  Original exception: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.
Trace ID: bbe2ba97-375c-4b46-b089-d11963257700
Correlation ID: 1b3232a9-e22e-48de-adc0-bbfe5d7b8a68
Timestamp: 2020-06-09 15:33:49Z

@MarkAtAgilliance
Copy link

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. #10816. @schaabs has put a fix in.

@TomMalow
Copy link

Thank @MarkAtAgilliance for mentioning the AZURE_USERNAME. Resolved my issue by checking that variable.

I had tried to resolve my issue previously by setting my username through the AZURE_USERNAME variable. However, in my haste, I had written my email with a different domain than the subscriptions i was targeting. Updating the username to correct domain, or removing the environment entirely, resolved my issue.

@spmanjunath
Copy link

spmanjunath commented Jul 3, 2020

I'm having exactly the same issue as alhardy. Not sure what is going wrong.
But I do have the full calls tack:

Azure.Identity.AuthenticationFailedException
  HResult=0x80131500
  Message=DefaultAzureCredential authentication failed.
  Source=Azure.Identity
  StackTrace:
   at Azure.Identity.DefaultAzureCredential.<GetTokenImplAsync>d__11.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
   at Azure.Identity.DefaultAzureCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.<AuthenticateRequestAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.<ProcessCoreAsync>d__8.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   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.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
   at Azure.Core.Pipeline.RetryPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipeline.Send(HttpMessage message, CancellationToken cancellationToken)
   at Azure.Core.Pipeline.HttpPipeline.SendRequest(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest[TResult](RequestMethod method, Func`1 resultFactory, CancellationToken cancellationToken, String[] path)
   at Azure.Security.KeyVault.Secrets.SecretClient.GetSecret(String name, String version, CancellationToken cancellationToken)
   at BestelBoer.Registrations.Registrations.GetSecret(SecretClient client, String key) in C:\git\bestelboer\BackendWebsite\BestelBoer.Registrations\Registrations.cs:line 106

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
AuthenticationFailedException: SharedTokenCacheCredential authentication failed.

Inner Exception 2:
MsalServiceException: A configuration issue is preventing authentication - check the error message from the server for details.You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details.  Original exception: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.
Trace ID: bbe2ba97-375c-4b46-b089-d11963257700
Correlation ID: 1b3232a9-e22e-48de-adc0-bbfe5d7b8a68
Timestamp: 2020-06-09 15:33:49Z

@Rolorob : Were you able to resolve this issue? I am seeing similar stack trace and unable to proceed forward. Thanks.

@Rolorob
Copy link

Rolorob commented Jul 3, 2020

I'm having exactly the same issue as alhardy. Not sure what is going wrong.
But I do have the full calls tack:

Azure.Identity.AuthenticationFailedException
  HResult=0x80131500
  Message=DefaultAzureCredential authentication failed.
  Source=Azure.Identity
  StackTrace:
   at Azure.Identity.DefaultAzureCredential.<GetTokenImplAsync>d__11.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
   at Azure.Identity.DefaultAzureCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.<AuthenticateRequestAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.<ProcessCoreAsync>d__8.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   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.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()
   at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
   at Azure.Core.Pipeline.RetryPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
   at Azure.Core.Pipeline.HttpPipeline.Send(HttpMessage message, CancellationToken cancellationToken)
   at Azure.Core.Pipeline.HttpPipeline.SendRequest(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest[TResult](RequestMethod method, Func`1 resultFactory, CancellationToken cancellationToken, String[] path)
   at Azure.Security.KeyVault.Secrets.SecretClient.GetSecret(String name, String version, CancellationToken cancellationToken)
   at BestelBoer.Registrations.Registrations.GetSecret(SecretClient client, String key) in C:\git\bestelboer\BackendWebsite\BestelBoer.Registrations\Registrations.cs:line 106

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
AuthenticationFailedException: SharedTokenCacheCredential authentication failed.

Inner Exception 2:
MsalServiceException: A configuration issue is preventing authentication - check the error message from the server for details.You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details.  Original exception: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.
Trace ID: bbe2ba97-375c-4b46-b089-d11963257700
Correlation ID: 1b3232a9-e22e-48de-adc0-bbfe5d7b8a68
Timestamp: 2020-06-09 15:33:49Z

@Rolorob : Were you able to resolve this issue? I am seeing similar stack trace and unable to proceed forward. Thanks.

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

@xperiandri
Copy link

Tried 1.2.0-preview.1-1.2.0-preview.5 works only with interactive auth and AZURE_USERNAME and AZURE_TENANT_ID

var credentialOptions = new DefaultAzureCredentialOptions
{
    ExcludeInteractiveBrowserCredential = false,
    ExcludeVisualStudioCodeCredential = true
};
var credential = new DefaultAzureCredential(credentialOptions);

If ExcludeVisualStudioCodeCredential = false then exception.
If ExcludeInteractiveBrowserCredential = true and ExcludeVisualStudioCodeCredential = true then cannot find my Microsoft Account in cache.

@joshnoe
Copy link

joshnoe commented Sep 25, 2020

In my case, my AZURE_USERNAME was 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 -> -> Profile (the default selection), and look at "Name" in the Identity section.

@MarkAtAgilliance
Copy link

assume you mean AZURE_USERNAME not AZURE_NAME.

@schaabs
Copy link
Member

schaabs commented Sep 30, 2020

There are several issues that are currently being tracked in here. In order to allow us to make progress, we are closing this issue as we believe the original issue has been addressed. Anyone who has replied with related issue they feel still hasn't been addressed, please open a new issue so we can address it specifically.

@schaabs schaabs closed this as completed Sep 30, 2020
@Rrusl
Copy link

Rrusl commented Nov 16, 2020

Hi all,
This issue has arose again in "Azure.Identity" Version="1.3.0".
Everething works well in "Azure.Identity" Version="1.2.0".

@kevinv21
Copy link

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 facing the same issue when using "Azure.Identity" Version="1.2.3". Downgrading the version to "Azure.Identity" Version="1.2.0" solves the problem for me. Thanks!!

@TorbenPhilippsen
Copy link

TorbenPhilippsen commented Jan 9, 2021

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 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;
}

@dancundy
Copy link

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

This worked for me.

@ffroliva
Copy link

I faced problems with DefaultAzureCredential with a single account.

I was able to over come this problem with a different type of Credential: ClientSecretCredential

        String keyVaultUri = "https://<YOUR_KEY_VAULT>.vault.azure.net/";

        TokenCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientSecret("<YOUR_CLIENT_SECRET>")
                .clientId("<YOUR_CLIENT_ID>")
                .tenantId("<YOUR_TENANT_ID>")
                .build();
        SecretClient secretClient = new SecretClientBuilder()
                .vaultUrl(keyVaultUri)
                .credential(clientSecretCredential)
                .buildClient();
...
// do what you want

pom.xml

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-security-keyvault-secrets</artifactId>
      <version>4.2.7</version>
    </dependency>

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-identity</artifactId>
      <version>1.2.5</version>
    </dependency>

@github-actions github-actions bot locked and limited conversation to collaborators Mar 29, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Azure.Identity Client This issue points to a problem in the data-plane of the library.
Projects
None yet
Development

No branches or pull requests