azureweb-applicationsazure-data-explorerkql

Azure Data Explorer - Kusto query: unauthorized error querying from an Azure AD application


I would like to create a web application where to run ADX queries. I followed the instruction here https://learn.microsoft.com/en-us/azure/data-explorer/provision-azure-ad-app
to create and register the AAD application with ADX

Here the code

    var kustoConnectionStringBuilder = new KustoConnectionStringBuilder(<ADX cluster uri/database>);
    kustoConnectionStringBuilder.WithAadApplicationKeyAuthentication(<ApplicationId>, <Application Secret>, <TenantID>);
    var kustoClient = KustoClientFactory.CreateCslQueryProvider(kustoConnectionStringBuilder.ConnectionString);
    var query = "AdtPropertyEvents\r\n| count";
var reader = kustoClient.ExecuteQuery(query);

The ExecuteQuery call is giving an unauthorized error

Unauthorized (401-Unauthorized)


Solution

  • I followed the same document and I created an application with the necessary API permission user_impersonation to access azure data explorer and make sure to grant admin consent to your permission like below:

    enter image description here

    You need to create the database and add permission to your Application like below:

    enter image description here

    Once you have added you can follow this code to run the query using C#

    Code:

        using Kusto.Data;
        using Kusto.Data.Net.Client;
        using static System.Net.WebRequestMethods;
        
        class Program
        {
            static void Main(string[] args)
            {
                // Replace placeholders with actual values
                string clusterUri = "https://<clustername>.<location>.kusto.windows.net";
                string database = "your-database-name";
                string applicationId = "your-app-id";
                string applicationSecret = "your-app-secret";
                string tenantId = "your tenant id";
        
                var kcp = new KustoConnectionStringBuilder(clusterUri, database).WithAadApplicationKeyAuthentication(applicationId, applicationSecret, tenantId);
                var kustoClient = KustoClientFactory.CreateCslQueryProvider(kcp);
        
                string query = "table1 | count";
                var reader =kustoClient.ExecuteQuery(query);
        
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetInt64(0));
                }
            }
        }
    

    Output:

    The above code was executed and successfully returned the count of table1 in my database.

    1000
    

    enter image description here