- 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:
- In the first step, the client:
- Communicate with the Azure AD service.
- Authenticating to the Azure AD service.
- Request an access token issued specifically for your cluster.
- 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:
https://help.kusto.windows.net
Alternatively, clients can also request an access token with a static cloud resource ID, such as
https://kusto.kusto.windows.net
(for public cloud services). Clients doing this must ensure that they only base their hostname suffix (here,kusto.windows.net 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-4349ca6bfe24
and domain namecontoso.com
.
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
https://login.microsoftonline.com/{tenantId}
. here,{tenant identifier}
is the organization's tenant ID in Azure AD or its domain name (for example,contoso.com
).When the tenant hosting the authenticatee is unknown, the "public" endpoint can be used instead
{tenant identifier}
reach valueCommon
.
use
The Azure AD service endpoint for authentication is also known asAzure AD permissions URLor simplyAzure AD permissions.
use
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 variableAadAuthoridadUri
to 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.
use
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 certification
connection 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 = "https://..kusto.windows.net";// Create a public authentication client for Azure AD: var authClient = PublicClientApplicationBuilder.Create("").WithAuthority($"https://login.microsoftonline.com/").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 = "https://..kusto.windows.net";// Create a confidential authentication client for Azure AD: var authClient = ConfidentialClientApplicationBuilder.Create("").WithAuthority($"https://login.microsoftonline.com/").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 )) ;
Authentication
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
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).
In the resources panel, selectAzure Active Directory, soapplication log.
Find the application that uses streaming on its behalf and open it.
chooseAPI Rights, soadd license.
Find an app by nameAzure Data Explorerand select it.
chooseuser_impersonation / correct access.
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($"https://login.microsoftonline.com/").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 [] { "https://..kusto.windows.net/.default" }, // 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("https://..kusto.windows.net") .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.
detail
The authentication code flow is used when the client executes JavaScript code in the user's browser. The authentication process consists of two phases:
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.
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.
use
- Receive an ID token by calling
PublicClientApplication.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.
Create MSAL instance
PublicClientApplicationPublicClientApplication
:import * as msal from "@azure/msal-browser"; const msalConfig = { auth: { clientId: "
", source: "https://login.microsoftonline.com/ ", },};const msalInstance = new msal.PublicClientApplication(msalConfig); great
Make sure your app always calls you
handleRedirectPromise()
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();
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: ["https://help.kusto.windows.net/.default"] , } ); } catch (err) { console.err(err); // handle errors} }
Add calling code
msalInstance.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:// help.kusto.windows.net/.default"], }; 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;
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( "https://help.kusto.windows.net/v2/rest/query", { 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];