Azure / azure-kusto-samples-dotnet

Azure Data Explorer (ADX) sample code
MIT License
54 stars 41 forks source link

How to authenticate using Microsoft.Azure.Services.AppAuthentication? #3

Closed empz closed 4 years ago

empz commented 4 years ago

I'm using Azure Kusto .NET SDK (Kusto.Data) library and I want to use the library Microsoft.Azure.Services.AppAuthentication so that I can use managed identities on Azure but my own developer account when running locally as shown here: https://docs.microsoft.com/en-us/azure/key-vault/service-to-service-authentication#local-development-authentication

I'm having a hard time trying to put the pieces together. I'm able to get an access token but then I'm not sure how to use it for the request.

var kustoClusterUri = "https://myclustername.westus2.kusto.windows.net";
var dbName = "MyDatabase";
var azureServiceTokenProvider = new AzureServiceTokenProvider();

string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(kustoClusterUri).ConfigureAwait(false);

KustoConnectionStringBuilder kcsb = new KustoConnectionStringBuilder(kustoClusterUri, dbName)
var queryProvider = KustoClientFactory.CreateCslQueryProvider(kcsb);

var requestProperties = new ClientRequestProperties {
    ClientRequestId = Guid.NewGuid().ToString(),
    SecurityToken = accessToken, // ???
    User = azureServiceTokenProvider.PrincipalUsed.UserPrincipalName // ???
};

var query = ".show tables";
queryProvider.ExecuteQuery(dbName, query, requestProperties);

Getting Unauthorized error.

I couldn't find any documentation on how to do this. Maybe using some of the methods in KustoConnectionStringBuilder? Maybe WithAadTokenProviderAuthentication() ?

empz commented 4 years ago

Found it!

var kustoClusterUri = "https://kusto-cluster-url";
var azureServiceTokenProvider = new AzureServiceTokenProvider();

var kcsb = new KustoConnectionStringBuilder(kustoClusterUri)
    .WithAadTokenProviderAuthentication(
        () => azureServiceTokenProvider.GetAccessTokenAsync(kustoClusterUri).GetAwaiter().GetResult()
    );
zzgzy commented 4 years ago

@eparizzi Hi Emiliano, .Dump() no longer works and I tried .Dispose() but got error saying "Cannot access a disposed object.". Have you seen this error? Thank you in advance!

empz commented 4 years ago

@zzgzy .Dump() is just an extension method provided by LINQPad. No need to use it.

You have the working example on my second comment.

jykallam commented 3 months ago

@empz where do you managed identity to generate the token?