There is a workaround which is using azure active directory app permissions for connecting with azure log analytic workspace from c#. But whether the same can be achieved through managed identity instead of using Active Directory.
I created a User Assigned Managed Identity:
Granted Log Analytics API permission by using the below PowerShell script:
Connect-AzureAD
$TenantID="TenantID"
$LogAppId = "ca7f3f0b-7d91-482c-8e09-c5d840d0eac5" --> Dont change this value
$NameOfMSI="testrukMI"
$PermissionName = "Data.Read"
$MSI = (Get-AzureADServicePrincipal -Filter "displayName eq '$NameOfMSI'")
Start-Sleep -Seconds 10
$LogServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq '$LogAppId'"
$AppRole = $LogServicePrincipal.AppRoles |
Where-Object {$_.Value -eq $PermissionName -and $_.AllowedMemberTypes -contains "Application"}
New-AzureAdServiceAppRoleAssignment -ObjectId $MSI.ObjectId -PrincipalId $MSI.ObjectId -ResourceId $LogServicePrincipal.ObjectId -Id $AppRole.Id
Check whether the API permission is assigned to the managed identity like below:
Go to Enterprise Application -> Search your managed identity -> Permissions
I assigned Log Analytics Reader role to the Managed Identity:
Now generate the access token using the below code:
using System;
using Azure.Identity;
using Azure.Core;
class Program
{
static async Task Main(string[] args)
{
string clientId = "XXXXXXXX"; // The Client ID of the user assigned identity
AccessToken token = await new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = clientId
})
.GetTokenAsync(
new TokenRequestContext(
new[] { "https://westus2.api.loganalytics.io/.default" }
));
Console.WriteLine(token.Token);
}
}
Decoded access token:
Using the above generated access token, I am able to access the Log Analytic workspace successfully:
https://api.loganalytics.io/v1/workspaces/WorkSpaceID/query