question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] Azure.Identity: DefaultAzureCredential does not work with Azure CLI in 1.2.0-preview-2

See original GitHub issue

Describe the bug When using Azure.Identity 1.2.0-preview.2 and DefaultAzureCredential it does not pick up the credentials from logging in with Azure CLI (az login)

Downgrading to Azure.Identity 1.2.0-preview.1 works fine.

Expected behavior That preview 2 works the same way as preview 1

Actual behavior (include Exception or Stack Trace)

> dotnet run
Unhandled exception. Microsoft.Extensions.Configuration.AzureAppConfiguration.KeyVaultReferenceException: DefaultAzureCredential authentication failed.. ErrorCode:, Key:Password, Label:dev, Etag:*******, SecretIdentifier:https://keyvault.vault.azure.net/secrets/Password
 ---> Azure.Identity.AuthenticationFailedException: DefaultAzureCredential authentication failed.
 ---> Azure.Identity.AuthenticationFailedException: VisualStudioCodeCredential authentication failed.
 ---> MSAL.NetCore.4.11.0.0.MsalUiRequiredException:
        ErrorCode: invalid_grant
Microsoft.Identity.Client.MsalUiRequiredException: AADSTS700082: The refresh token has expired due to inactivity. The token was issued on 2018-10-15T06:43:20.0560859Z and was inactive for 90.00:00:00.
Trace ID: 6f298095-ab4a-40c6-b4a7-cd459f751100
Correlation ID: 56daf9a9-81f4-41f9-9f8e-83bf3712d3d4
Timestamp: 2020-04-28 09:51:54Z
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext, Boolean addCorrelationId)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.GetTokenAsync(Uri endPoint, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint)
   at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary`2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.SendTokenRequestAsync(String tokenEndpoint, IDictionary`2 additionalBodyParameters, CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.ByRefreshTokenRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ClientApplicationBaseExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenByRefreshTokenParameters refreshTokenParameters, CancellationToken cancellationToken)
   at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalPublicClient.AcquireTokenWithDeviceCodeAsync(String[] scopes, String storedCredentials, AzureCloudInstance azureCloudInstance, String tenant, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.VisualStudioCodeCredential.GetTokenImplAsync(TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
        StatusCode: 400
        ResponseBody: {"error":"invalid_grant","error_description":"AADSTS700082: The refresh token has expired due to inactivity. The token was issued on 2018-10-15T06:43:20.0560859Z and was inactive for 90.00:00:00.\r\nTrace ID: 6f298095-ab4a-40c6-b4a7-cd459f751100\r\nCorrelation ID: 56daf9a9-81f4-41f9-9f8e-83bf3712d3d4\r\nTimestamp: 2020-04-28 09:51:54Z","error_codes":[700082],"timestamp":"2020-04-28 09:51:54Z","trace_id":"6f298095-ab4a-40c6-b4a7-cd459f751100","correlation_id":"56daf9a9-81f4-41f9-9f8e-83bf3712d3d4","error_uri":"https://login.microsoftonline.com/error?code=700082","suberror":"bad_token"}
        Headers: Cache-Control: no-store, no-cache
Pragma: no-cache
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
client-request-id: 56daf9a9-81f4-41f9-9f8e-83bf3712d3d4
x-ms-request-id: 6f298095-ab4a-40c6-b4a7-cd459f751100
x-ms-ests-server: 2.1.10433.14 - DUB1 ProdSlices
x-ms-clitelem: 1,700082,0,48481714022.7457,
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: fpc=; expires=Thu, 28-May-2020 09:51:54 GMT; path=/; secure; HttpOnly; SameSite=None,x-ms-gateway-slice=prod; path=/; SameSite=None; secure; HttpOnly,stsservicecookie=ests; path=/; secure; HttpOnly; SameSite=None
Date: Tue, 28 Apr 2020 09:51:53 GMT

   --- End of inner exception stack trace ---
   at Azure.Identity.VisualStudioCodeCredential.GetTokenImplAsync(TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.VisualStudioCodeCredential.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.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthenticateRequestAsync(HttpMessage message, Boolean async)
   at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.ProcessCoreAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
   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.Core.Pipeline.HttpPipeline.SendRequestAsync(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequestAsync(Request request, CancellationToken cancellationToken)
   at Azure.Security.KeyVault.KeyVaultPipeline.SendRequestAsync[TResult](RequestMethod method, Func`1 resultFactory, CancellationToken cancellationToken, String[] path)
   at Azure.Security.KeyVault.Secrets.SecretClient.GetSecretAsync(String name, String version, CancellationToken cancellationToken)
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureKeyVault.AzureKeyVaultSecretProvider.GetSecretValue(Uri secretUri, CancellationToken cancellationToken)
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureKeyVault.AzureKeyVaultKeyValueAdapter.ProcessKeyValue(ConfigurationSetting setting, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureKeyVault.AzureKeyVaultKeyValueAdapter.ProcessKeyValue(ConfigurationSetting setting, CancellationToken cancellationToken)
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureAppConfigurationProvider.ProcessAdapters(ConfigurationSetting setting, CancellationToken cancellationToken)
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureAppConfigurationProvider.SetData(IDictionary`2 data, CancellationToken cancellationToken)
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureAppConfigurationProvider.LoadAll(Boolean ignoreFailures)
   at Microsoft.Extensions.Configuration.AzureAppConfiguration.AzureAppConfigurationProvider.Load()
   at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Justify.Dsf.Web.Program.Main(String[] args) in C:\dev\Web\Program.cs:line 13

To Reproduce Steps to reproduce the behavior (include a code snippet, screenshot, or any additional information that might help us reproduce the issue)

ASP.NET Core app with the following Startup code:

public static IHostBuilder CreateHostBuilder(string[] args) =>
	Host.CreateDefaultBuilder(args)
		.ConfigureWebHostDefaults(webBuilder =>
		{
			webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
				{
					var settings = config.Build();
					var environmentName = settings["EnvironmentName"] ?? "dev";
					var appName = "App";
					config.AddAzureAppConfiguration(options =>
					{
						options.Connect(new Uri(settings["AppConfig:EndPoint"]), new DefaultAzureCredential())
							.Select("Shared:*", LabelFilter.Null)
							.Select("Shared:*", environmentName)
							.Select($"{appName}:*", LabelFilter.Null)
							.Select($"{appName}:*", environmentName)
							.TrimKeyPrefix("Shared:")
							.TrimKeyPrefix($"{appName}:")
							;
						options.ConfigureKeyVault(kv => { kv.SetCredential(new DefaultAzureCredential()); });
					});
				})
				.UseStartup<Startup>();
		});

Environment:

  • Name and version of the Library package used: Azure.Identity 1.2.0-preview.2
  • Hosting platform or OS and .NET runtime version (dotnet --info output for .NET Core projects):
.NET Core SDK (reflecting any global.json):
 Version:   3.1.300-preview-015115
 Commit:    cd8d468337

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.19041
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.1.300-preview-015115\

Host (useful for support):
  Version: 3.1.2
  Commit:  916b5cba26
  • IDE and version : Visual Studio 16.6.0 Preview 4 installed, but running from the command line with dotnet run

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
schaabscommented, May 20, 2020

This fix for this has been merged in #11716 and will be released in 1.2.0-preview.4 in our June release. I’m closing this issue for now, please reopen if you are still having issues with this package once released.

0reactions
henriksencommented, May 18, 2020

Hi

Thanks for the suggestions! As you say, the preview.3 did not fix the problem, but the ExcludeVisualStudioCodeCredential = true workaround did indeed work around the problem. Thanks!

Read more comments on GitHub >

github_iconTop Results From Across the Web

DefaultAzureCredential, InteractiveBrowserCredential, etc.. ...
I'm aware that certain processes can and can't be spawned from the browser; however, what's causing the error is server-side code that shouldn't ......
Read more >
Azure Identity client library for .NET
It's a known issue that VisualStudioCodeCredential doesn't work with Azure Account extension versions newer than 0.9.11. A long-term fix to this problem is...
Read more >
Azure Identity client library for .NET
If the environment configuration is not present or incomplete, the DefaultAzureCredential will then determine if a managed identity is available in the current ......
Read more >
Azure.Identity 1.10.0
This is the implementation of the Azure SDK Client Library for Azure Identity. ... To authenticate with the Azure CLI, users can run...
Read more >
Azure.Identity.AuthenticationFailedException: - Microsoft Q&A
The error message implies that the authentication failed. Did you sign in into the Visual Studio code using the same Azure credentials that...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found