Azure App - Azure.Identity.CredentialUnavailableException: Azure CLI not installed - azure

I have a console app that I am deploying to Azure App Services. The app runs fine when running on my local computer, but when I publish it to Azure, I get the following error:
Application: w3wp.exe
CoreCLR Version: 6.0.922.41905
.NET Version: 6.0.9
Description: The process was terminated due to an unhandled exception.
Exception Info: Azure.Identity.CredentialUnavailableException: Azure CLI not installed
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)
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)
...
The code for accessing the key vault look like this:
AuthenticationConfiguration authenticationConfiguration = new AuthenticationConfiguration();
_configuration.Bind("Authentication", authenticationConfiguration);
SecretClient keyVaultClient = new SecretClient(
new Uri(_configuration.GetValue<string>("KeyVaultUri")),
new DefaultAzureCredential());
authenticationConfiguration.AccessTokenSecret = keyVaultClient.GetSecret("access-token-secret").Value.Value;
services.AddSingleton(authenticationConfiguration);
How do I install Azure CLI in Azure Web Service (or how do I properly access the key vault in my Console App)?

Publishing the app as Self-Contained fixed the problem.

Related

.NET 5 on IIS - Could not load file or assembly 'DotNetAgent, Version=1.0.0.0'

.NET5 applications throwing error after deploying to IIS.
Unhandled exception. System.IO.FileNotFoundException: Could not load file or assembly 'DotNetAgent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=87b69d96e75fbfca'. The system cannot find the file specified.
File name: 'DotNetAgent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=87b69d96e75fbfca'
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at AG.MatterSphere.Web.API.Program.Main(String[] args)
You can try to "Enable 32 bit Applications" in Application Pool to solve this issue.
Select Application Pools under the Web Server name in the left window.
In the Application Pools window, right-click AppPool and select Advanced Settings.
Under the General section, set Enable 32-Bit Applications to True.
Click OK to save the changes.

Azure DevOps 2020 - GraphClient

I can't find an easy way to communicate to Microsoft AzureDevops team.
I'm working on some tools that are working with Azure 2019 and there's also Azure 2020 RC right now. Microsoft deprecated SOAP API for 2019. And 2020 also, for REST Client.
Thou in 2019 REST client is not fully provided. GraphClient: https://learn.microsoft.com/en-us/rest/api/azure/devops/graph/?view=azure-devops-rest-6.0 is missing there. That means, no way to get UserGraph and Users, but through SOAP API the old way.
I though that maybe with Azure 2020 it's gonna be changed, but actually no.
I'm using Microsoft.VisualStudio.Services.Client in newest preview and latest stable version. That are: 16.173.0-preview and 16.153.0. Calling it manually making REST requests won't help either.
My test code:
var uriToServer = new Uri("http://localhost:81/DefaultCollection");
var vssBasicCredential = new VssCredentials(new WindowsCredential(new NetworkCredential("test", "test")));
using var vssConnection = new VssConnection(uriToServer, vssBasicCredential);
using var graphHttpClient = vssConnection.GetClient<GraphHttpClient>();
var listUsersAsync = await graphHttpClient.ListUsersAsync();
And we're getting:
handled Exception: System.AggregateException: One or more errors occurred. (API resource location 005e26ec-6b77-4e4f-a986-b3827bf241f5 is not registered on http://localhost:81/DefaultCollection.) --->
Microsoft.VisualStudio.Services.WebApi.VssResourceNotFoundException: API resource location 005e26ec-6b77-4e4f-a986-b3827bf241f5 is not registered on http://localhost:81/DefaultCollection.
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.CreateRequestMessageAsync(HttpMethod method, IEnumerable`1 additionalHeaders, Guid locationId, Object routeValues, ApiResourceVersion version, HttpContent content,
IEnumerable`1 queryParameters, Object userState, CancellationToken cancellationToken, String mediaType)
at Microsoft.VisualStudio.Services.Graph.Client.GraphHttpClient.ListUsersAsync(IEnumerable`1 subjectTypes, String continuationToken, Object userState, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at ConsoleApp1.Program.Main(String[] args) in C:\Users\user\RiderProjects\ConsoleApp1\ConsoleApp1\Program.cs:line 17
The same problem as with 2019. Of course other clients are working perfectly.
The same code works perfectly for Azure DevOps Cloud - just have to change VssCredentials to VssBasicCredentials. Thou Basic I know can work for server if SSL is active.
Yes, currently graph api is not available for Azure DevOps Server 2019 and Server 2020.
You could add your request for this feature on our UserVoice site, which is our main forum for product suggestions. After suggest raised, you can vote and add your comments for this feedback. The product team would provide the updates if they view it.
As an alternative, you can try to use azure cli. With the Azure DevOps extension for Azure Command Line Interface (CLI), you can manage many Azure DevOps Services from the command line.
The Azure DevOps Command Line Interface (CLI) is available for Azure
DevOps Server 2020 and Azure DevOps Services.
About getting started with Azure DevOps CLI ,please refer to this document.

ASP.Net Core 3.1 Error Load Azure Key Vault On Azure App Service

I Use ASP.Net Core 3.1 and I deploy it on Azure App Service (Web) On Linux.
the question is, when i deploy the code on Azure App Service, i got error message:
Unhandled exception. System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString)
at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretsWithHttpMessagesAsync(String vaultBaseUrl, Nullable`1 maxresults, Dictionary`2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.GetSecretsAsync(IKeyVaultClient operations, String vaultBaseUrl, Nullable`1 maxresults, CancellationToken cancellationToken)
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.LoadAsync()
at Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.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 ZHFSoftware.Program.Main(String[] args) in / home / runner / work / ZHFSoftware / ZHFSoftware / ZHFSoftware / Program.cs:line 19
ptrace(ATTACH, 29) FAILED Operation not permitted
i know this is PERMISSION error related.
and when i run the web,
:( Application Error
If you are the application administrator, you can access the diagnostic resources.
i can run the code in DEVELOPMENT and PRODUCTION, but on LOCALHOST (and i can get the azure key vault)
but NOT in the Deploy version.
(https://.azurewebsites.net/) => Got Error
i already set the permission based on the manual :
https://learn.microsoft.com/en-us/azure/key-vault/managed-identity
https://learn.microsoft.com/en-us/azure/azure-app-configuration/howto-integrate-azure-managed-service-identity?tabs=core2x
https://wakeupandcode.com/key-vault-for-asp-net-core-3-1-web-apps/
and i follow the youtube manual:
https://www.youtube.com/watch?v=k2VYcYS3EIA
but no use. still error.
Any help will appreciated.
thanks.
Today, i solved my problem.
i "Publish" my web project from Visual Studio 2019 Preview.
and Configure "Service Dependencies", and then Publish.
MY Website Running ...
i push to my github and found this item added.
"serviceDependencies. - Web Deploy.json"
and i open the file, it contains:
{
"dependencies": {
"secrets1": {
"resourceId": "/subscriptions/<subscriptionId>/resourceGroups/<resGroudId>/providers/Microsoft.KeyVault/vaults/<Key Vault Name>",
"type": "secrets.keyVault",
"connectionId": "ASPNETCORE_HOSTINGSTARTUP__KEYVAULT__CONFIGURATIONVAULT"
}
}
}
NB: the Manual from
https://learn.microsoft.com/en-us/azure/spring-cloud/spring-cloud-github-actions-key-vault very useful. thanks Microsoft ^^/

Azure Service Bus 1.1 Failing to Start

Service Bus Gateway is not starting.
First of all I have tried completely uninstalling all Azure/Fabric/Service Bus type SDKs and installations. I have installed both Windows Azure Pack: Service Bus 1.1 and Windows Azure Pack: Security Update for Service Bus 1.1 (KB2972621) from scratch.
After deleting all service bus related databases I start the Service Bus Configuration wizard and begin starting a new farm with custom settings.
I leave everything default except adding my own certificates, and of course entering my password.
After clicking go the the service bus configuration wizard eventually gets stuck in progress:
Starting
Created and configured Service Bus farm management database.
Created and configured Service Bus gateway database.
Creating default container.
Processing completed
Validating input and configuration parameters.
Granting 'Log on as Service' privilege to the run as account.
Windows Fabric configuration started.
Running Windows Fabric deployment.
Windows Fabric starting.
Service Bus configuration started.
Updating database.
Service Bus services starting.
The event viewer logs for Microsoft-Service Bus > Operational has the following errors. Top error received first...
Exception during fabric service creation for container 1, Exception System.ArgumentException: At least one address must be provided if hostEndpoints is non-null
Parameter name: hostEndpoints
at System.Fabric.FabricClient.InitializeFabricClient(SecurityCredentials credential, TimeSpan keepAliveInterval, String[] hostEndpoints)
at System.Fabric.FabricClient..ctor(SecurityCredentials credential, String[] hostEndpoints)
at Microsoft.ServiceBus.Commands.ServiceBusGetCommands.CreateFabricClient()
at Microsoft.ServiceBus.Commands.ServiceBusCommandBase.RegisterWinFabricService(Int64 containerId)
And then:
Service Bus Gateway service failed to start, retry count 1. Exception message: An error occurred creating the configuration section handler for namespacePolicyDataStoreFactory: Could not load file or assembly 'Microsoft.Cloud.Common.AzureStorage, Version=2.1.0.0, Culture=neutral, PublicKeyToken=4fe77f22fa8374f3' or one of its dependencies. The system cannot find the file specified.. Stack Trace: at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
at System.Configuration.BaseConfigurationRecord.CreateSectionDefault(String configKey, Boolean getRuntimeObject, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at Microsoft.Cloud.ServiceBus.ServiceRegistryManagerContext.CreateNamespacePolicyDataManager(IComponentSite site)
at Microsoft.Cloud.ServiceBus.ServiceRegistryManagerContext.LoadServices(IComponentSite site)
at Microsoft.Cloud.ServiceBus.Common.Components.ComponentFactoryBase`1.CreateComponent()
at Microsoft.Cloud.HostingModel.ComponentHost.CreateComponent(IComponentFactory componentFactory)
at Microsoft.Cloud.HostingModel.ComponentHost.CreateComponents()
at Microsoft.Cloud.HostingModel.ComponentHost.Open()
at Microsoft.ServiceBus.Gateway.Gateway.OnStart(String[] args)
In Services the relevant services have the following statuses:
Service Bus Gateway: Starting
Service Bus Message Broker: Stopped
Service Bus Resource Provider: Stopped
Thanks
If you received this error after updating to NET framework v4.6+ then
Microsoft have a fix for this now, download this Update for Service Bus Server 1.1 (KB3086798) http://www.microsoft.com/en-us/download/details.aspx?id=49496
TL;DR;
Download dropbox.com/s/cb5fro1rv... - thanks Arash Rahimi
Navigate to your SDK tools
sn -Vr Microsoft.Cloud.Common.AzureStorage.dll
gacutil /i Microsoft.Cloud.Common.AzureStorage.dll
This issue was caused by installing the Visual Studio 2015 RC. Thankfully someone else has already experienced this and an answer has been posted.
Please see this answer on How do I report a bug in Windows Server Service Bus?
For whatever reason if the Dropbox link becomes obsolete. I have added it to Github.
Make sure any/all RabbitMQ service(s) are all stopped. (Or anything that uses the AMQP protocol)

Are blob StorageExceptions to be expected when using Azure App Service Logging?

Every 30 or 40 minutes I see the following exception when streaming application logs from our Azure Website sorry.... Azure Web App :-)
Application: Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (400) Bad Request. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
Application: at System.Net.HttpWebRequest.GetResponse()
Application: at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext)
Application: --- End of inner exception stack trace ---
Application: at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext)
Application: at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.PutBlockList(IEnumerable`1 blockList, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
Application: at Microsoft.WindowsAzure.WebSites.Diagnostics.AzureBlobTraceListener.AppendStreamToBlob(Stream stream)
Application: at Microsoft.WindowsAzure.WebSites.Diagnostics.AzureBlobTraceListener.ConsumeBuffer()
Application: Request Information
Application: RequestDate:Thu, 26 Mar 2015 22:58:05 GMT
Application: StatusMessage:The specified block list is invalid.
Application: ErrorCode:InvalidBlockList
Is this to be expected when you have diagnostic logging enabled on an Azure App Service? Is it just a First Chance Exception to just ignore?
The exception stack trace does not include your Service Bus Queue call, so it should not be caused by you calling SendAsync. AzureBlobTraceListener is a .NET trace listener that uploads all the trace and debug output to Azure Blob service. It looks like it is experiencing an issue while uploading those blobs.
We confirmed that this is a bug in AzureBlobTraceListener and it is now fixed. Thank you for reporting this and we apologize for the inconvenience.
If, however, your App service logging was not supposed to be enabled in the first place, please see Enable diagnostics logging for web apps in Azure App Service for more information.

Resources