Azure / azure-sdk-for-net

This repository is for active development of the Azure SDK for .NET. For consumers of the SDK we recommend visiting our public developer docs at https://learn.microsoft.com/dotnet/azure/ or our versioned developer docs at https://azure.github.io/azure-sdk-for-net.
MIT License
5.47k stars 4.8k forks source link

[BUG] DefaultAzureCredential failed to retrieve a token from the included credentials #17113

Closed AliGuemues closed 3 years ago

AliGuemues commented 3 years ago

Describe the bug After switching from Azure.Identity 1.2.0 to Azure.Identity 1.3.0 I get the following error while debugging my ASP .NET Core 3.1.8 Application:

DefaultAzureCredential failed to retrieve a token from the included credentials.
- ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found.
- SharedTokenCacheCredential authentication unavailable. Token acquisition failed for user . Ensure that you have authenticated with a developer tool that supports Azure single sign on.
- Process "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\b1hwzg3d.j4s\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token.  'AADSTS500011: The resource principal named https://database.windows.net/default was not found in the tenant named X. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.
Timestamp: 2020-11-20 12:14:23Z'

While using Azure.Identity 1.2.0 I had already issues with following bug: https://github.com/Azure/azure-sdk-for-net/issues/14691

Now what I am doing:

I switched our application and resources for the use of managed identities. For debugging I am using the "Azure Service Authentication" option in Visual Studio 2019. The error occurs not in a deterministic timeframe. Sometimes my application is working for about an hour without problems and sometimes the error occurs after few minutes.

This is a snippet where I get the exception:

            if(Database.GetDbConnection() is Microsoft.Data.SqlClient.SqlConnection conn)
            {
                var tokenCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions() 
                { 
                    ExcludeAzureCliCredential = true, 
                    ExcludeVisualStudioCodeCredential = true, 
                });

                var context = new TokenRequestContext(new[] { "https://database.windows.net/default" });
                var tokenResponse = tokenCredential.GetToken(context);
                conn.AccessToken = tokenResponse.Token;
            }

I experiment with the DefaultAzureCredentialOptions. But it makes no difference if I use the DefaultAzureCredentialOptions or not:

       if(Database.GetDbConnection() is Microsoft.Data.SqlClient.SqlConnection conn)
            {
                var tokenCredential = new DefaultAzureCredential();

                var context = new TokenRequestContext(new[] { "https://database.windows.net/default" });
                var tokenResponse = tokenCredential.GetToken(context);
                conn.AccessToken = tokenResponse.Token;
            }

After a while my application crashes.

Environment:

jsquire commented 3 years ago

Thank you for your feedback. Tagging and routing to the team member best able to assist.

schaabs commented 3 years ago

@AliGuemues thanks for filing this issue. Sorry your having this trouble. Looking at the error message it seems that the VisualStudioCredential is failing with the following error which is complaining about the scope that you've passed in "https://database.windows.net/default".

Process "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\b1hwzg3d.j4s\TokenService\Microsoft.Asal.TokenService.exe" has failed with unexpected error: TS003: Error, TS004: Unable to get access token.  'AADSTS500011: The resource principal named https://database.windows.net/default was not found in the tenant named X. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant'

I believe the scope you meant to specify is "https://database.windows.net/.default" (note the . before default). If you update the scope do you still see authentication failures?

AliGuemues commented 3 years ago

@schaabs thanks for your quick response. I changed the scope of the URL like you mentioned and it seems to work. I tested my application for about an hour without any problems.

So its my fault to check the URL of the scope. But I am wondering about why this was working with the wrong scope URL for quite of time and failed in a non deterministic timeframe. I set breakpoints on the code and their was no exception for let me guess hundred times and then the exception occured.

Do you have any explanation for this behaviour?

Greetings

christothes commented 3 years ago

Hi @AliGuemues I'm going to close this issue for now - but if you can reproduce the behavior with the wrong scope set, please re-open with the details.

vishveshtrivedi commented 1 year ago

Hello, I am having Similar Issue. When I try to run the following thing on gitlab it gives me error.

if credential is None: credential = azure.identity.DefaultAzureCredential(exclude_shared_token_cache_credential=True) self.credential = credential if kv_name is None: kv_name = os.getenv("AZURE_KV_NAME") url = f"https://{kv_name}.vault.azure.net" super().init(url, credential, **kwargs)

Result: Failure Exception: ClientAuthenticationError: DefaultAzureCredential failed to retrieve a token from the included credentials. Attempted credentials: EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot.this issue. ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint. SharedTokenCacheCredential: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache. AzureCliCredential: Azure CLI not found on path AzurePowerShellCredential: PowerShell is not installed To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot. Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 452, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, self.kwargs) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 718, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/extension.py", line 215, in _raw_invocation_wrapper result = function(args) File "/home/site/wwwroot/regatta_association/init.py", line 26, in main con_in = api.get_northstar_connection(secrets_manager := api.SecretsManager()) File "/home/site/wwwroot/api/database.py", line 43, in get_northstar_connection username = secrets_manager.get_secret_value("northstar-db-username") File "/home/site/wwwroot/api/secrets.py", line 39, in get_secret_value return self.get_secret(name, version, kwargs).value # type: ignore File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer return func(args, kwargs) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/keyvault/secrets/_client.py", line 72, in get_secret bundle = self._client.get_secret( File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/keyvault/secrets/_generated/_operations_mixin.py", line 1574, in get_secret return mixin_instance.get_secret(vault_base_url, secret_name, secret_version, kwargs) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/tracing/decorator.py", line 78, in wrapper_use_tracer return func(args, kwargs) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/keyvault/secrets/_generated/v7_3/operations/_key_vault_client_operations.py", line 694, in get_secret pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/_base.py", line 205, in run return first_node.send(pipeline_request) # type: ignore File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/_base.py", line 69, in send response = self.next.send(request) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/_base.py", line 69, in send response = self.next.send(request) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/_base.py", line 69, in send response = self.next.send(request) [Previous line repeated 2 more times] File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/policies/_redirect.py", line 160, in send response = self.next.send(request) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/policies/_retry.py", line 474, in send response = self.next.send(request) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/policies/_authentication.py", line 126, in send request_authorized = self.on_challenge(request, response) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/keyvault/secrets/_shared/challenge_auth_policy.py", line 117, in on_challenge self.authorize_request(request, scope, tenant_id=challenge.tenant_id) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/core/pipeline/policies/_authentication.py", line 106, in authorize_request self._token = self._credential.get_token(*scopes, *kwargs) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/identity/_credentials/default.py", line 168, in get_token return super(DefaultAzureCredential, self).get_token(scopes, **kwargs) File "/home/site/wwwroot/.python_packages/lib/site-packages/azure/identity/_credentials/chained.py", line 101, in get_token raise ClientAuthenticationError(message=message)

Can anyone help me out in this?