Authenticating with Azure AD for access (2023)

  • article

The recommended way to access the cluster is through authenticationAzure Active Directory (Azure AD)service; this ensures the privacy of the accessing principal's directory credentials.

To do this, the client needs to perform two steps:

  1. In the first step, the client:
    1. Communicate with the Azure AD service.
    2. Authenticating to the Azure AD service.
    3. Request an access token issued specifically for your cluster.
  2. In the second step, the client makes a request to your cluster, providing the access token obtained in the first step as proof of identity for your cluster.

The request is then performed on behalf of the principal for whom Azure AD issued the access token. All authorization checks are performed using this identity.

In most cases, it is recommended to use one of Kusto's SDKs to access services programmatically, as they take a lot of the hassle out of implementing the process (and more). For more information, see.NET Development KitThe .Authentication property is created byKusto connection stringIf this is not possible, read on for details on how to implement this process yourself.

The main authentication scenarios are:

  • A client application that authenticates a logged-in userIn this case, an interactive application (client) triggers a request from Azure AD to the user for credentials such as username and password. consultUser Authentication,

  • "Headless" applications.In this case, the application runs without the user providing credentials. Instead, the app authenticates to Azure AD as "itself" using some of the credentials it configures. consultapplication authentication.

  • AuthenticationIn this case, sometimes referred to as a "web service" or "web application" scenario, an application receives an Azure AD access token from another application and "converts" it to another one that can be used in your cluster Azure AD access token for access. In other words, the application acts as an intermediary between the user or application providing the credentials and the engine service. consultAuthentication.

Azure AD resource specification

When purchasing access tokens from Azure AD, customers must indicate whichAzure AD resourcesA token must be issued. The Azure AD resource for an endpoint is the URI of the endpoint, excluding path and port information. For example:

Alternatively, clients can also request an access token with a static cloud resource ID, such as

(for public cloud services). Clients doing this must ensure that they only base their hostname suffix (here, website). Sending an access token to an untrusted service endpoint may result in a token leak, allowing the receiving service to perform operations on any Kusto service endpoint accessed by the master server.

Specify the Azure AD tenant ID

Azure AD is a multi-tenant service, and each organization can create aindexDirectory objects on Azure AD contain security-related objects such as user accounts, applications, and groups. Azure AD is commonly referred to in the directory astenant.Azure AD tenants are represented by a GUID (tenant number). In many cases, an Azure AD tenant can also be identified by the organization's domain name.

For example, an organization named "Contoso" might have a tenant ID4da81d62-e0a8-4899-adad-4349ca6bfe24and domain

Azure AD source endpoint specification

Azure AD has several endpoints for authentication:

  • When the tenant hosting the authenticated host is known (in other words, when the Azure AD directory where the user or application resides is known), the Azure AD endpoint is{tenantId}. here,{tenant identifier}is the organization's tenant ID in Azure AD or its domain name (for example,

  • When the tenant hosting the authenticatee is unknown, the "public" endpoint can be used instead{tenant identifier}reach valueCommon.


The Azure AD service endpoint for authentication is also known asAzure AD permissions URLor simplyAzure AD permissions.


Azure AD service endpoint changed to National Cloud. When using a cluster deployed in a national cloud, configure the corresponding national Azure AD cloud service endpoint. To change the endpoint, set the environment variableAadAuthoridadUrito the desired URI.

Azure AD local token cache

When using the Kusto SDK, Azure AD tokens are stored in a per-user token cache on the local machine (a file named%APPDATA%\Kusto\userTokenCache.datacan only be accessed or decrypted by logged-in users). Checks the cache for tokens before prompting the user for credentials, which reduces the number of times the user is prompted for credentials.


Azure AD token caching reduces the number of interactive messages, but doesn't completely eliminate them. Additionally, users cannot predict when they will be prompted for credentials. This means that if you need to support non-interactive logins (such as when scheduling a job), you should not attempt to authenticate with a user account, because that's when the credentials of the logged-in user need to be provided. The request will fail if executed using a non-interactive connection.

User Authentication

The easiest way to access a cluster with user authentication is to use the Kusto SDK and configurefederal certificationconnection string property areal.The first time a request is made to the service using the SDK, the user will see a login form to enter their Azure AD credentials. After successful authentication, the request will be sent.

Apps that don't use the Kusto SDK can still use itMicrosoft Authentication Library (MSAL)Instead of implementing the Azure AD service security protocol client. I understandAzure AD 和 OpenID ConnectFor example how to do this from a .NET application.

If your application is designed to act as an interface and authenticate users to an Azure Data Explorer cluster, your application must have permissions granted to Azure Data Explorer. The full step-by-step process is atConfigure permissions assigned to application registration.

The following short code snippet shows the usageMicrosoft Authentication Library (MSAL)Get an Azure AD user token to access the cluster (starts the login UI):

var kustoUri = "";// Create a public authentication client for Azure AD: var authClient = PublicClientApplicationBuilder.Create("").WithAuthority($"").WithRedirectUri("").Explorer Complex).ExecuteAsync().Result;// Extract the bearer access token var bearerToken = result.AccessToken;// Create an HTTP request and set the authorization header in your request: var request = WebRequest.Create ( new Uri (kustoUri) );request.Headers.Set(HttpRequestHeader.Authorization, string.Format(CultureInfo.InvariantCulture, "{0} {1 }", "Bearer", bearer token));

application authentication

The following short code snippet shows the usageMicrosoft Authentication Library (MSAL)Get an application token from Azure AD to access the cluster. There will be no prompts during this process, the application must be registered with Azure AD and equipped with the necessary credentials to authenticate the application (such as an Azure AD issued application key or an X509v2 certificate previously registered with Azure AD).

var kustoUri = "";// Create a confidential authentication client for Azure AD: var authClient = ConfidentialClientApplicationBuilder.Create("").WithAuthority($"").WithClientSecret("") // Can be replaced with .WithCertificate to authenticate with an X.509 certificate.Build(); // Get an application token for Azure Data Explorer: var result = authClient.AcquireTokenForClient( new[] { $" {kustoUri} / . default" } // Define the fields to access the Azure Data Explorer cluster).ExecuteAsync().Result;// Extract the bearer access token var bearerToken = result.AccessToken;// Create an HTTP request and authorize Set headers to your request: var request = WebRequest.Create(new Uri(kustoUri)); request.Headers.Set(HttpRequestHeader.Authorization, string.Format(CultureInfo.InvariantCulture, "{0} {1}", " Bearer", bearerToken )) ;


In this case, the application has been sent an Azure AD access token for an arbitrary resource managed by the application, and is used to obtain a new Azure AD access token for that resource so that the application Programs can access it. Kusto on the principal name indicated by the original Azure AD access token.

This process is calledOAuth2 Token Exchange FlowIt typically requires multiple configuration steps of Azure AD, and in some cases (depending on the Azure AD tenant configuration), may require specific consent from the Azure AD tenant administrator.

Step 1 - Establish a trust relationship between your application and the cluster

  1. Open itblue doorAnd make sure you are logged in to the correct tenant (see top right corner for the ID used to log into the portal).

  2. In the resources panel, selectAzure Active Directory, soapplication log.

  3. Find the application that uses streaming on its behalf and open it.

  4. chooseAPI Rights, soadd license.

  5. Find an app by nameAzure Data Explorerand select it.

  6. chooseuser_impersonation / correct access.

  7. chooseAdd permissions.

Step 2: Run the token exchange in your server code

// Create a confidential authentication client for Azure AD: var authClient = ConfidentialClientApplicationBuilder.Create("").WithAuthority($"").WithClientSecret("") // Can be replaced with .WithCertificate to authenticate with an X.509 certificate.Build(); // Obtain a user token on behalf of an interactive user of Azure Data Explorer based on the provided token: var result = authClient. AcquireTokenOnBehalfOf ( new [] { "" }, // Set scope to access Azure Data Explorer cluster new UserAssertion("" ) // encode the "raw" token for exchange).ExecuteAsync().Result; var accessTokenForAdx = result.AccessToken;

Step 3 - Provide the token to the Kusto client library and run the query

// Cree KustoConnectionStringBuilder usando el tokenvar de Azure AD adquirido previamente connectionStringBuilder = νέο KustoConnectionStringBuilder("") .WithAadUserTokenAuthentication(accessTokenForAdx);// 使用 var queryClient = KustoClientFactory.CreateCslQueryProvider(connectionStringBuilderliultsqueryExeery = .nc("","", zero);

Web Client Authentication and Authorization (JavaScript)

Azure AD application configuration

In addition to the templatepaceTo configure your Azure AD application, you also need to enable Single Page Application (SPA) settings in your Azure AD application. This allows OAuth authorization codes to flow with PKCE to use tokensMSAL.js 2.0(MSAL 1.0 uses the less secure indirect authorization flow.) Use the steps in MSAL 2.0 toSPA application registration scriptConfigure the application accordingly.


The authentication code flow is used when the client executes JavaScript code in the user's browser. The authentication process consists of two phases:

  1. The app will redirect you to sign in to Azure AD. After you log in, Azure AD redirects you to the application with the authorization code in the URI.

  2. The application makes a request to the token endpoint to obtain an access token. The token is valid for 24 hours, during which time clients can reuse it by obtaining it silently.

Similar to the native client process, there must be two Azure AD applications (server and client) with a configured relationship between them.


  • Receive an ID token by callingPublicClientApplication.loginRedirect()method and access token are obtained by callingPublicClientApplication.acquireTokenSilent(), thisPublicClientApplication.acquireTokenRedirect()In case the implied takeover fails. MSAL 2.0 also supportsPublicClientApplicationloginPopup(), but some browsers block pop-ups, making them less useful than redirects.
  • MSAL 2.0 requires a login (aka get token ID) before any access token calls can be made.

MSAL.js 2.0 has detailed sample applications for different frameworks like React and Angular. For an example of how to authenticate to a cluster with a React app using MSAL.js 2.0 , seeMSAL.js 2.0 React Example.For other frameworks, see the MSAL.js 2.0 documentation for the sample application.

Here's an example of framework-independent code to link toassistanceclub.

  1. Create MSAL instancePublicClientApplicationPublicClientApplication:

    import * as msal from "@azure/msal-browser"; const msalConfig = { auth: { clientId: "", source: "", },};const msalInstance = new msal.PublicClientApplication(msalConfig);


    Make sure your app always calls youhandleRedirectPromise()every page load. This is because Azure AD adds the authorization code as part of the URI, andhandleRedirectPromise()This function extracts the authorization code from the URI and caches it.

    espera msalInstance.handleRedirectPromise();
  2. If MSAL does not have a local cache account, add the code to log in. Consider using the redirect field on the Azure AD page to give your application the necessary permissions to access the cluster.

    const myAccounts = msalInstance.getAllAccounts();// If it is not a login account, redirect the user to log in. // No return statement is needed here because the browser will redirect the user to the login page. login.if ( myAccounts === undefined || myAccounts.length === 0) { try { await msalInstance.loginRedirect({ scopes: [""] , } ); } catch (err) { console.err(err); // handle errors} }
  3. Add calling codemsalInstance.acquireTokenSilent()Get the actual access token needed to access the specified cluster. If silent token acquisition fails, callbuyTokenRedirect()Get a new token.

    const accounts = myAccounts[0]; const name = account name; window.document.getElementById("main").innerHTML = `Hi ${name}!`; const accessTokenRequest = { account, scope: ["https://"], }; let getTokenResult = undefined; try { acquireTokenResult = expect msalInstance.acquireTokenSilent( accessTokenRequest ); } catch ( error ) { // if access token/update/id already Expired, we should redirect to AAD to get a new one. if (InteractionRequiredAuthError instance error) { expect msalInstance.acquireTokenRedirect(accessTokenRequest); } } const accessToken = getTokenResult.accessToken;
  4. Finally, add the code that makes the request to the specified cluster. You need to add the token toauthorizedattribute in the request header for successful authentication. For example, the following code requests to run the querysampleThe database is located atassistanceclub.

    const fetchResult = await fetch( "", { headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json ", }, method: "POST", body: JSON.stringify({ db: "Samples", csl: "StormEvents | count", }), } ); const jsonResult = await fetchResult.json(); // Next The first cell of a line outputting result data const count = jsonResult.filter((x) => x.TableKind == "PrimaryResult")[0].Rows[0][0];


Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated: 07/16/2023

Views: 6034

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.