in order to programmatically retrive some AppTraces and AppExceptions info from an Azure Application Insights Logs resource, we followed the instructions included in the following article advicing to adopt the new Azure Monitor Query client library for .NET to fulfill the purpose.
https://learn.microsoft.com/it-it/dotnet/api/overview/azure/Monitor.Query-readme?view=azure-dotnet
Strictly following the above article instructions (and using the DefaultAzureCredential object to authenticate), we managed to get the client library's LogsQueryClient object working fine in the local version of the developed web api (ASP .NET Core 6.0). And so, locally we are eable to fetch the logs info we need. But once we published the web api on the Cloud (under the same Azure subscription of the Application Insights target resource) we started to get the following error:
N.B. Surprisingly we didn't find any thread explaining, step by step how to fix the problem with specific reference to the new Azure Monitor Query client library.
To fix the issue, we tried replacing the class DefaultAzureCredential with the class ClientSecretCredential generating and assigning it a new client secret.
Here are the details concerning the steps we followed to implement the ClientSecretCredentials. In particular, we have:
Unfortunately, replacing the class DefaultAzureCredential with ClientSecretCredential didn't work and the error message keeps to be the same.
N.B.
Here are the code snippets:
Program.cs
builder.Services.AddAzureClients(builder =>
{
static LogsQueryClient func(LogsQueryClientOptions options)
{
options.Retry.Mode = Azure.Core.RetryMode.Exponential;
options.Retry.MaxRetries = 5;
var csc = new ClientSecretCredential(tenantId, clientId, clientSecret);
return new LogsQueryClient(csc, options);
}
builder.AddClient<LogsQueryClient, LogsQueryClientOptions>(func);
var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret);
builder.UseCredential(credentials);
});
Controller.cs (get logsQueryClient through dependency injection)
Response<LogsQueryResult> response = await logsQueryClient.QueryWorkspaceAsync(workSpaceId, query);
Thanks for your appreciated help. We finally managed to spot where the problem was.
After the point 3 listed in our original post: <<Assign to the Registered App (AAD Application) the "Reader Role" for the Application Insights acting from the resource's Access control (IAM) section of the Azure Portal.>>
... We omitted to do the same thing for the Log Analytics workspace. Each Application Insight resource refers infact to a specific Workspace. For that reason, it is necessary to assign the same reader role to the Registered App also for the above workspace. Log Analytics workspaces too have infact an Access control (IAM) section in the Azure Portal, just like the other resources.
Assigning this role to the AAD registered app the issue was fixed.