Share via


Query's uitvoeren op gegevens met MATLAB

MATLAB is een programmeer- en numeriek computingplatform dat wordt gebruikt voor het analyseren van gegevens, het ontwikkelen van algoritmen en het maken van modellen. In dit artikel wordt uitgelegd hoe u een autorisatietoken kunt ophalen in MATLAB voor Azure Data Explorer en hoe u het token gebruikt om te communiceren met uw cluster.

Vereisten

Selecteer het tabblad voor het besturingssysteem dat wordt gebruikt om MATLAB uit te voeren.

  1. Download de pakketten Microsoft Identity Client en Microsoft Identity Abstractions van NuGet.

  2. Pak de gedownloade pakketten en DLL-bestanden uit van lib\net45 naar een map naar keuze. In dit artikel gebruiken we de map C:\Matlab\DLL.

Gebruikersverificatie uitvoeren

Bij gebruikersverificatie wordt de gebruiker gevraagd zich aan te melden via een browservenster. Na een geslaagde aanmelding wordt een gebruikersautorisatietoken verleend. In deze sectie wordt beschreven hoe u deze interactieve aanmeldingsstroom configureert.

Gebruikersverificatie uitvoeren:

  1. Definieer de constanten die nodig zijn voor de autorisatie. Zie Verificatieparameters voor meer informatie over deze waarden.

    % The Azure Data Explorer cluster URL
    clusterUrl = 'https://<adx-cluster>.kusto.windows.net';
    % The Azure AD tenant ID
    tenantId = '';
    % Send a request to https://<adx-cluster>.kusto.windows.net/v1/rest/auth/metadata
    % The appId should be the value of KustoClientAppId
    appId = '';
    % The Azure AD scopes
    scopesToUse = strcat(clusterUrl,'/.default ');
    
  2. Laad in MATLAB Studio de uitgepakte DLL-bestanden:

    % Access the folder that contains the DLL files
    dllFolder = fullfile("C:","Matlab","DLL");
    
    % Load the referenced assemblies in the MATLAB session
    matlabDllFiles = dir(fullfile(dllFolder,'*.dll'));
    for k = 1:length(matlabDllFiles)
        baseFileName = matlabDllFiles(k).name;
        fullFileName = fullfile(dllFolder,baseFileName);
        fprintf(1, 'Reading  %s\n', fullFileName);
    end
        % Load the downloaded assembly in MATLAB
        NET.addAssembly(fullFileName);
    
  3. Gebruik de PublicClientApplicationBuilder om een gebruiker te vragen zich interactief aan te melden:

    % Create an PublicClientApplicationBuilder
    app = Microsoft.Identity.Client.PublicClientApplicationBuilder.Create(appId)...
        .WithAuthority(Microsoft.Identity.Client.AzureCloudInstance.AzurePublic,tenantId)...
        .WithRedirectUri('http://localhost:8675')...
        .Build();
    
    % System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    NET.setStaticProperty ('System.Net.ServicePointManager.SecurityProtocol',System.Net.SecurityProtocolType.Tls12)
    % Start with creating a list of scopes
    scopes = NET.createGeneric('System.Collections.Generic.List',{'System.String'});
    % Add the actual scopes
    scopes.Add(scopesToUse);
    fprintf(1, 'Using appScope  %s\n', scopesToUse);
    
    % Get the token from the service
    % and show the interactive dialog in which the user can login
    tokenAcquirer = app.AcquireTokenInteractive(scopes);
    result = tokenAcquirer.ExecuteAsync;
    
    % Extract the token and when it expires
    % and retrieve the returned token
    token = char(result.Result.AccessToken);
    fprintf(2, 'User token aquired and will expire at %s & extended expires at %s', result.Result.ExpiresOn.LocalDateTime.ToString,result.Result.ExtendedExpiresOn.ToLocalTime.ToString);
    
  4. Gebruik het autorisatietoken om een query uit te voeren op uw cluster via de REST API:

    options=weboptions('HeaderFields',{'RequestMethod','POST';'Accept' 'application/json';'Authorization' ['Bearer ', token]; 'Content-Type' 'application/json; charset=utf-8'; 'Connection' 'Keep-Alive'; 'x-ms-app' 'Matlab'; 'x-ms-client-request-id' 'Matlab-Query-Request'});
    
    % The DB and KQL variables represent the database and query to execute
    querydata = struct('db', "<DB>", 'csl', "<KQL>");
    querryresults  = webwrite("https://sdktestcluster.westeurope.dev.kusto.windows.net/v2/rest/query", querydata, options);
    
    % Extract the results row
    results=querryresults{3}.Rows
    

Toepassingsverificatie uitvoeren

Microsoft Entra toepassingsautorisatie kan worden gebruikt voor scenario's waarin interactieve aanmelding niet gewenst is en geautomatiseerde uitvoeringen nodig zijn.

Toepassingsverificatie uitvoeren:

  1. Een Microsoft Entra-toepassing inrichten. Voor de omleidings-URI selecteert u Web en invoer http://localhost:8675 als de URI.

  2. Definieer de constanten die nodig zijn voor de autorisatie. Zie Verificatieparameters voor meer informatie over deze waarden.

    % The Azure Data Explorer cluster URL
    clusterUrl = 'https://<adx-cluster>.kusto.windows.net';
    % The Azure AD tenant ID
    tenantId = '';
    % The Azure AD application ID and key
    appId = '';
    appSecret = '';
    
  3. Laad in MATLAB Studio de uitgepakte DLL-bestanden:

     % Access the folder that contains the DLL files
     dllFolder = fullfile("C:","Matlab","DLL");
    
     % Load the referenced assemblies in the MATLAB session
     matlabDllFiles = dir(fullfile(dllFolder,'*.dll'));
     for k = 1:length(matlabDllFiles)
         baseFileName = matlabDllFiles(k).name;
         fullFileName = fullfile(dllFolder,baseFileName);
         fprintf(1, 'Reading  %s\n', fullFileName);
     end
         % Load the downloaded assembly
         NET.addAssembly(fullFileName);
    
  4. Gebruik ConfidentialClientApplicationBuilder om een niet-interactieve geautomatiseerde aanmelding uit te voeren met de Microsoft Entra-toepassing:

    %  Create an ConfidentialClientApplicationBuilder
    app = Microsoft.Identity.Client.ConfidentialClientApplicationBuilder.Create(appId)...
        .WithAuthority(Microsoft.Identity.Client.AzureCloudInstance.AzurePublic,tenantId)...
        .WithRedirectUri('http://localhost:8675')...
        .WithClientSecret(appSecret)...
        .Build();
    
    % System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    NET.setStaticProperty ('System.Net.ServicePointManager.SecurityProtocol',System.Net.SecurityProtocolType.Tls12)
    % Start with creating a list of scopes
    scopes = NET.createGeneric('System.Collections.Generic.List',{'System.String'});
    % Add the actual scopes
    scopes.Add(scopesToUse);
    fprintf(1, 'Using appScope  %s\n', scopesToUse);
    
    % Get the token from the service and cache it until it expires
    tokenAcquirer = app.AcquireTokenForClient(scopes);
    result = tokenAcquirer.ExecuteAsync;
    
    % Extract the token and when it expires
    % retrieve the returned token
    token = char(result.Result.AccessToken);
    fprintf(2, 'User token aquired and will expire at %s & extended expires at %s', result.Result.ExpiresOn.LocalDateTime.ToString,result.Result.ExtendedExpiresOn.ToLocalTime.ToString);
    
  5. Gebruik het autorisatietoken om een query uit te voeren op uw cluster via de REST API:

    options=weboptions('HeaderFields',{'RequestMethod','POST';'Accept' 'application/json';'Authorization' ['Bearer ', token]; 'Content-Type' 'application/json; charset=utf-8'; 'Connection' 'Keep-Alive'; 'x-ms-app' 'Matlab'; 'x-ms-client-request-id' 'Matlab-Query-Request'});
    
    % The DB and KQL variables represent the database and query to execute
    querydata = struct('db', "<DB>", 'csl', "<KQL>");
    querryresults  = webwrite("https://sdktestcluster.westeurope.dev.kusto.windows.net/v2/rest/query", querydata, options);
    
    % Extract the results row
    results=querryresults{3}.Rows
    
  • Query's uitvoeren op uw cluster met de REST API