Unable to connect to azure cli from program.cs Any help is appreciated. Simple Program.cs and error posted in details

Unable to connect to azure cli from program.cs Any help is appreciated. Simple Program.cs and error posted below

Program.cs

---------------------------------------

 

 

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

var dummySecretName = "AdmsApimKey";

Console.WriteLine("Managed Identity based Key Vault access tester");

Console.WriteLine("==============================================");


//
// Issue with Azure KeyVault access when using Managed Identity on a developer's local machine
//

// Similar Issue reported: https://github.com/Azure/azure-sdk-for-python/issues/23245

//
// Solution arrived at using DefaultAzureCredentialOptions 
//   Idea/reference at : https://blog.jongallant.com/2021/08/azure-identity-201/
//

// Works!
var options = new DefaultAzureCredentialOptions
{
    //ExcludeEnvironmentCredential = true,
    ExcludeManagedIdentityCredential = true,
    //ExcludeVisualStudioCredential = true,
    //ExcludeVisualStudioCodeCredential = true
};

// EnvironmentCredential - inspects values from environment variables
// ManagedIdentityCredential - uses auth from managed identity
// SharedTokenCacheCredential - uses auth from local shared token cache used by some versions of VS
// VisualStudioCredential - uses auth from VS
// VisualStudioCodeCredential - uses auth from VS Code

var credentialsWithExclusionOption = new DefaultAzureCredential(options);
var secretClientWithDefaultCredentionsWithExclusionOption = new SecretClient(new Uri("https://pplz-key-omex-d.vault.azure.net/"), credentialsWithExclusionOption);
var secretValue = await secretClientWithDefaultCredentionsWithExclusionOption.GetSecretAsync(dummySecretName);
Console.WriteLine($"Using Credentials With ExclusionOption: The dummy secret is {secretValue?.Value.Value}");

// Works! - when logged in using 'az cli' or 'Azure login with Device Code in JetBrains Rider'
var credentialsUsingAzureCliLogin = new AzureCliCredential();
var secretClientWithAzureCliLogin = new SecretClient(new Uri("https://pplz-key-omex-d.vault.azure.net/"), credentialsUsingAzureCliLogin);
secretValue = await secretClientWithAzureCliLogin.GetSecretAsync(dummySecretName);
Console.WriteLine($"Using AzureCliLogin Credentials: The dummy secret is {secretValue?.Value.Value}");

//
// DOES NOT WORK! - throws  401 - Unauthorized exception on my box - but works on other DEVs boxes 
//    - possibly due to missing 'Visiual Studio and its cached credentials and the Azure handles Visual Studio 'DefaultCredentials' on my box?
//
var defaultzureCredentials = new DefaultAzureCredential();
var secretClientWithDefaultzureCredentials = new SecretClient(new Uri("https://pplz-key-omex-d.vault.azure.net/"), defaultzureCredentials);
secretValue = await secretClientWithDefaultzureCredentials.GetSecretAsync(dummySecretName);
Console.WriteLine($"Using DefaultzureCredentials: The dummy secret is {secretValue?.Value.Value}");

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

-----------------------

Error

 

-----------------------------

 

Azure.Identity.CredentialUnavailableException: DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot
- EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
- WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/workloadidentitycredential/troubleshoot
- No installed instance of Visual Studio was found
- Please run 'az login' to set up account
- Please run 'Connect-AzAccount' to set up account.
- Please run 'azd auth login' from a command prompt to authenticate before using this credential.
---> System.AggregateException: Multiple exceptions were encountered while attempting to authenticate. (EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot) (WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/workloadidentitycredential/troubleshoot) (No installed instance of Visual Studio was found) (Please run 'az login' to set up account) (Please run 'Connect-AzAccount' to set up account.) (Please run 'azd auth login' from a command prompt to authenticate before using this credential.)
---> Azure.Identity.CredentialUnavailableException: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.EnvironmentCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.EnvironmentCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
  --- End of inner exception stack trace ---
---> (Inner Exception #1) Azure.Identity.CredentialUnavailableException: WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/workloadidentitycredential/troubleshoot
  at Azure.Identity.WorkloadIdentityCredential.GetTokenCoreAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.WorkloadIdentityCredential.GetTokenCoreAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.WorkloadIdentityCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)<---

---> (Inner Exception #2) Azure.Identity.CredentialUnavailableException: No installed instance of Visual Studio was found
  at Azure.Identity.VisualStudioCredential.GetTokenImplAsync(TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.VisualStudioCredential.GetTokenImplAsync(TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.VisualStudioCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)<---

---> (Inner Exception #3) Azure.Identity.CredentialUnavailableException: Please run 'az login' to set up account
  at Azure.Identity.AzureCliCredential.RequestCliAccessTokenAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
  at Azure.Identity.AzureCliCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.AzureCliCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.AzureCliCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)<---

---> (Inner Exception #4) Azure.Identity.CredentialUnavailableException: Please run 'Connect-AzAccount' to set up account.
  at Azure.Identity.AzurePowerShellCredential.CheckForErrors(String output, Int32 exitCode)
  at Azure.Identity.AzurePowerShellCredential.RequestAzurePowerShellAccessTokenAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
  at Azure.Identity.AzurePowerShellCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.AzurePowerShellCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.AzurePowerShellCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)<---

---> (Inner Exception #5) Azure.Identity.CredentialUnavailableException: Please run 'azd auth login' from a command prompt to authenticate before using this credential.
  at Azure.Identity.AzureDeveloperCliCredential.RequestCliAccessTokenAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
  at Azure.Identity.AzureDeveloperCliCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.AzureDeveloperCliCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.AzureDeveloperCliCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)<---

  --- End of inner exception stack trace ---
  at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)
  at Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
  at Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Identity.DefaultAzureCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.SetResultOnTcsFromCredentialAsync(TokenRequestContext context, TaskCompletionSource`1 targetTcs, Boolean async, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetAuthHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](Task`1 task)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.TokenRequestState.GetCurrentHeaderValue(Boolean async, Boolean checkForCompletion, CancellationToken cancellationToken)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetAuthHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AuthenticateAndAuthorizeRequest(HttpMessage message, TokenRequestContext context)
  at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthorizeRequestOnChallengeAsyncInternal(HttpMessage message, Boolean async)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask`1 task)
  at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthorizeRequestOnChallenge(HttpMessage message)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
  at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
  at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory`1 pipeline)
  at Azure.Core.Pipeline.RedirectPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
  at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
  at Azure.Core.Pipeline.RedirectPolicy.Process(HttpMessage message, ReadOnlyMemory`1 pipeline)
  at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(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.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.GetPage[T](Uri firstPageUri, String nextLink, Func`1 itemFactory, String operationName, CancellationToken cancellationToken)
  at Azure.Security.KeyVault.Secrets.SecretClient.<>c__DisplayClass15_0.<GetPropertiesOfSecrets>b__0(String nextLink)
  at Azure.Core.PageResponseEnumerator.<>c__DisplayClass0_0`1.<CreateEnumerable>b__0(String continuationToken, Nullable`1 pageSizeHint)
  at Azure.Core.PageResponseEnumerator.FuncPageable`1.AsPages(String continuationToken, Nullable`1 pageSizeHint)+MoveNext()
  at Azure.Pageable`1.GetEnumerator()+MoveNext()
  at Azure.Extensions.AspNetCore.Configuration.Secrets.AzureKeyVaultConfigurationProvider.Load()
  at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
  at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
  at Microsoft.Extensions.Hosting.HostBuilder.InitializeAppConfiguration()
  at Microsoft.Extensions.Hosting.HostBuilder.Build()
  at PPL.OmEx.Alerts.FunctionApp.Program.Main(String[] args) in C:\Code\PPL.OmEx.FunctionApp\PPL.Alerts.FunctionApp\Program.cs:line 22

0
2 comments

I was having the same problem.

You'll need to have the “Azure Toolkit for Rider” plugin installed and make sure this option is enabled: https://github.com/JetBrains/azure-tools-for-intellij/issues/967#issuecomment-2527494022

0

Williams, thanks for the reply. It makes sense but I am still getting the same error when I do the above step.

 

Not sure why it is asking for these things?

 

- No installed instance of Visual Studio was found
- Please run 'az login' to set up account
- Please run 'Connect-AzAccount' to set up account.
- Please run 'azd auth login' from a command prompt to authenticate before using this credential.

0

Please sign in to leave a comment.