App authentication methods
Applies to: ✅ Microsoft Fabric ✅ Azure Data Explorer
This documentation provides an overview of the primary methods of authentication methods available for the Kusto client libraries. The provided code snippets demonstrate different approaches to authenticate users and apps, enabling seamless interaction with Kusto clusters. Each method is suitable for different scenarios and requirements.
Where possible, we recommend using managed identities instead of username and password authentication or connection strings. Managed identities provide a more secure and streamlined approach to authentication.
In this article, you learn how to authenticate using:
Application Principal
User Principal
- Interactive user sign-in authentication
- Azure Command-Line Interface (CLI) authentication
- Device code authentication
Custom Token Provider
Prerequisites
- Set up your development environment to use the Kusto client library.
Application Principal authentication methods
This section covers the different methods of authenticating using an application principal.
Managed Identity authentication
There are two types of managed identities: system-assigned and user-assigned. System-assigned managed identities have their lifecycle tied to the resource that created them. This identity is restricted to only one resource. User-assigned managed identities can be used on multiple resources. For more information, see Managed Identities.
| In the following examples, replace <QueryEndpointUri>
and <ManagedIdentityClientId>
with your own values.
System-assigned managed identity:
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>) .WithAadSystemManagedIdentity();
User-assigned managed identity. Use the identity client ID or object ID, as follows:
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>) .WithAadUserManagedIdentity(<ManagedIdentityClientId>);
Important
- The object, or principal, ID of the Managed Identity resource must be assigned a role to access the Kusto cluster. You can do this in the Azure portal in your Kusto cluster resource page under Security + networking > Permissions. Managed Identity should not be attached directly to the Kusto cluster.
- Managed Identity authentication is not supported in local development environments. To test Managed Identity authentication, deploy the application to Azure or use a different authentication method when working locally.
Certificate-based authentication
Certificates can serve as secrets to authenticate an application's identity when requesting a token. There are several methods to load the certificate, such as loading it from the machine's local credentials store or from disk.
| In the following examples, replace <QueryEndpointUri>
, <ApplicationId>
, <CertificateSubjectName>
, <CertificateIssuerName>
, <CertificateThumbprint>
, <CertificateObject>
, <AuthorityId>
, <PemPublicCertificate>
, <PemPrivateKey>
, <privateKeyPemFilePath>
, <PemCertificatePath>
, and <EnableSubjectAndIssuerAuth>
with your own values.
Certificate from the machine's local certificate store is only supported using C#:
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>) .WithAadApplicationSubjectAndIssuerAuthentication(<ApplicationId>, <CertificateSubjectName>, <CertificateIssuerName>, <AuthorityId>);
Important
When using subject name and issuer, the certificate must be installed in the local machine's certificate store.
Certificate from an arbitrary source, such as a file on disk, cache, or secure store like Azure Key Vault. The certificate object must contain a private key:
X509Certificate2 certificate = <CertificateObject>; var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>) .WithAadApplicationCertificateAuthentication(<ApplicationId>, certificate, <AuthorityId>);
For more information, see Kusto connection strings.
Important
To load certificates from Azure Key Vault, you can use the Azure.Security.KeyVault.Certificates client.
Application key authentication
Application key, also known as an application password, is a secret string that an application uses to authenticate and prove its identity when requesting a token. It serves as a form of credential for the application to access protected resources. The application key is typically generated and assigned by the identity provider or authorization server. It's important to securely manage and protect the application key to prevent unauthorized access to sensitive information or actions.
| In the following examples, replace <QueryEndpointUri>
, <ApplicationId>
, <ApplicationKey>
, <AuthorityId>
, and <AuthorityId>
with your own values.
Application key:
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>) .WithAadApplicationKeyAuthentication(<ApplicationId>, <ApplicationKey>, <AuthorityId>);
Connection string with application key:
var connectionString = "Data Source=<QueryEndpointUri>;Initial Catalog=NetDefaultDB;AAD Federated Security=True;AppClientId=<ApplicationId>;AppKey=<ApplicationKey>;Authority Id=<AuthorityId>;" var kcsb = new KustoConnectionStringBuilder(connectionString);
Important
Hard-coding secrets in your code is considered a bad practice. Storing sensitive information, such as authentication credentials, in plain text can lead to security vulnerabilities. We recommended that you keep sensitive information encrypted or store them securely in a key vault. By using encryption or a key vault, you can ensure that your secrets are protected and only accessible to authorized users or applications.
User Principal authentication methods
This section covers the different methods of authenticating using a user principal.
Interactive user sign-in authentication
This authentication method uses the user's credentials to establish a secure connection with Kusto. The method opens a web browser where the user is prompted to enter their username and password to complete the authentication process.
| In the following examples, replace <QueryEndpointUri>
,<AuthorityId>
, and <AuthorityId>
with your own values.
Interactive user sign-in:
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>) .WithAadUserPromptAuthentication();
Azure Command-Line Interface (CLI) authentication
This authentication method uses the Azure Command-Line Interface (CLI) to authenticate and obtain a token for the user. Running the az login
command means the user can securely establish a connection and retrieve the necessary token for authentication purposes. The user might be prompted to sign in if the token isn't available in the Azure CLI cache and the interactive
parameter is set to true
. For more information, see Azure Command-Line Interface (CLI).
| In the following example, replace <QueryEndpointUri>
with your own value.
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>)
.WithAadAzCliAuthentication(interactive: true);
Important
This method is only supported for .NET Framework apps.
Device code authentication
This method is designed for devices lacking a proper user interface for sign-in, such as IoT devices and server terminals. It provides the user with a code and a URL to authenticate using a different device, such as a smartphone. This interactive method requires the user to sign in through a browser.
| In the following example, replace <QueryEndpointUri>
with your own value.
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>)
.WithAadDeviceCodeAuthentication((msg, uri, code) =>
{
// The callback is used to display instructions to the user on how to authenticate using the device code
Console.WriteLine("Device Code Message: {0}", msg);
Console.WriteLine("Device Code Uri: {0}", uri);
Console.WriteLine("Device Code: {0}", code);
return Task.CompletedTask;
});
Important
Device code authentication may be blocked by tenant Conditional Access Policies. If this occurs, select an alternative authentication method.
Custom token provider authentication methods
This section covers the different methods of authenticating using a custom token provider.
Custom token provider for federated Managed Identity credential authentication
Custom token providers can be used to acquire a Microsoft Entra ID token for authentication. The following example demonstrates how to use a custom token provider to obtain a token using federated managed identity. You can modify the code to fit your application's requirements.
| In the following example, replace <AuthorityIdId>
, <ApplicationId>
, <ManagedIdentityClientId>
, and <QueryEndpointUri>
with your own values.
public class TokenProvider
{
private ClientAssertionCredential m_clientAssertion;
private TokenRequestContext m_tokenRequestContext;
public TokenProvider(string queryEndpointUri)
{
string resourceId = null;
try
{
// Get the appropiate resource id by querying the metadata
var httpClient = new HttpClient();
var response = httpClient.GetByteArrayAsync($"{queryEndpointUri}/v1/rest/auth/metadata").Result;
var json = JObject.Parse(Encoding.UTF8.GetString(response));
resourceId = json["AzureAD"]?["KustoServiceResourceId"]?.ToString();
// Append scope to resource id
resourceId = !string.IsNullOrWhiteSpace(resourceId) ? $"{resourceId}/.default" : null;
}
catch { /* Handle exception */}
m_tokenRequestContext = new TokenRequestContext(new string[] { resourceId ?? "https://kusto.kusto.windows.net/.default" });
// Create client assertion credential to authenticate with Kusto
m_clientAssertion = new ClientAssertionCredential
(
<AuthorityIdId>,
<ApplicationId>,
async (token) =>
{
// Get Managed Identity token
var miCredential = new ManagedIdentityCredential(<ManagedIdentityClientId>);
var miToken = await miCredential.GetTokenAsync(new TokenRequestContext(new[] {
"api://AzureADTokenExchange/.default"
})).ConfigureAwait(false);
return miToken.Token;
}
);
}
public async Task<string> GetTokenAsync()
{
var accessToken = await m_clientAssertion.GetTokenAsync(m_tokenRequestContext).ConfigureAwait(false);
return accessToken.Token;
}
}
var tokenProvider = new TokenProvider(<QueryEndpointUri>);
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>)
.WithAadTokenProviderAuthentication(
async () =>
{
return await tokenProvider.GetTokenAsync();
});
Using Azure TokenCredential authentication
Create a custom token provider by creating a class that inherits from TokenCredential
and implements the GetToken
method. Alternatively, you can use an existing token provider like DefaultAzureCredential
. This method provides flexibility for different authentication scenarios when a custom token provider is required.
You can use DefaultAzureCredential
for supporting production code that uses Managed Identity authentication, or testing code using Visual Studio or Azure CLI. DefaultAzureCredential
can be configured to use different authentication methods.
| In the following example, replace <QueryEndpointUri>
and <ManagedIdentityClientId>
with your own values.
var credentialProvider = new DefaultAzureCredential(new DefaultAzureCredentialOptions {
ManagedIdentityClientId = <ManagedIdentityClientId>
});
var kcsb = new KustoConnectionStringBuilder(<QueryEndpointUri>)
.WithAadAzureTokenCredentialsAuthentication(credentialProvider);
Note
DefaultAzureCredential
is used to authenticate with Azure services.
It attempts multiple authentication methods to obtain a token and can be configured to work with Managed Identity, Visual Studio, Azure CLI, and more.
This credential is suitable for both testing and production environments as it can be set up to use different authentication methods.
For more information, see DefaultAzureCredential Class.