Search code examples
azureazure-active-directoryazure-log-analyticsazure-managed-identity

How to connect Azure Log Analytic Workspace using managed identity from .Net API


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.

Reference : https://techcommunity.microsoft.com/t5/microsoft-sentinel-blog/access-azure-sentinel-log-analytics-via-api-part-1/ba-p/1248377.


Solution

  • I created a User Assigned Managed Identity:

    enter image description here

    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
    

    enter image description here

    Check whether the API permission is assigned to the managed identity like below:

    Go to Enterprise Application -> Search your managed identity -> Permissions

    enter image description here

    I assigned Log Analytics Reader role to the Managed Identity:

    enter image description here

    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);
        }
    }
    

    enter image description here

    Decoded access token:

    enter image description here

    Using the above generated access token, I am able to access the Log Analytic workspace successfully:

    https://api.loganalytics.io/v1/workspaces/WorkSpaceID/query
    

    enter image description here