Share via


Abfragen von Daten mithilfe von MATLAB

MATLAB ist eine Programmier- und Numerische Computing-Plattform, die zum Analysieren von Daten, Entwickeln von Algorithmen und Erstellen von Modellen verwendet wird. In diesem Artikel wird erläutert, wie Sie ein Autorisierungstoken in MATLAB für Azure Data Explorer abrufen und das Token für die Interaktion mit Ihrem Cluster verwenden.

Voraussetzungen

Wählen Sie die Registerkarte für das Betriebssystem aus, das zum Ausführen von MATLAB verwendet wird.

  1. Laden Sie die Pakete Microsoft Identity Client und Microsoft Identity Abstractions von NuGet herunter.

  2. Extrahieren Sie die heruntergeladenen Pakete und DLL-Dateien aus lib\net45 in einen Ordner Ihrer Wahl. In diesem Artikel verwenden wir den Ordner C:\Matlab\DLL.

Durchführen der Benutzerauthentifizierung

Bei der Benutzerauthentifizierung wird der Benutzer aufgefordert, sich über ein Browserfenster anzumelden. Nach erfolgreicher Anmeldung wird ein Benutzerautorisierungstoken gewährt. In diesem Abschnitt wird gezeigt, wie Sie diesen interaktiven Anmeldeflow konfigurieren.

So führen Sie die Benutzerauthentifizierung aus:

  1. Definieren Sie die für die Autorisierung erforderlichen Konstanten. Weitere Informationen zu diesen Werten finden Sie unter Authentifizierungsparameter.

    % 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. Laden Sie in MATLAB Studio die extrahierten DLL-Dateien:

    % 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. Verwenden Sie publicClientApplicationBuilder , um eine interaktive Benutzeranmeldung aufzufordern:

    % 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. Verwenden Sie das Autorisierungstoken, um Ihren Cluster über die REST-API abzufragen:

    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
    

Durchführen der Anwendungsauthentifizierung

Microsoft Entra Anwendungsautorisierung kann für Szenarien verwendet werden, in denen eine interaktive Anmeldung nicht gewünscht ist und automatisierte Ausführungen erforderlich sind.

So führen Sie die Anwendungsauthentifizierung aus:

  1. Stellen Sie eine Microsoft Entra-Anwendung zur Verfügung. Wählen Sie als Umleitungs-URIWeb und Eingabe http://localhost:8675 als URI aus.

  2. Definieren Sie die für die Autorisierung erforderlichen Konstanten. Weitere Informationen zu diesen Werten finden Sie unter Authentifizierungsparameter.

    % 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. Laden Sie in MATLAB Studio die extrahierten DLL-Dateien:

     % 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. Verwenden Sie confidentialClientApplicationBuilder, um eine nicht interaktive automatisierte Anmeldung mit der Microsoft Entra-Anwendung durchzuführen:

    %  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. Verwenden Sie das Autorisierungstoken, um Ihren Cluster über die REST-API abzufragen:

    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
    
  • Abfragen Ihres Clusters mit der REST-API