Wykonywanie zapytań dotyczących danych przy użyciu narzędzia MATLAB

MATLAB to platforma programowania i obliczeń liczbowych używana do analizowania danych, opracowywania algorytmów i tworzenia modeli. W tym artykule wyjaśniono, jak uzyskać token autoryzacji w narzędziu MATLAB dla platformy Azure Data Explorer oraz jak używać tokenu do interakcji z klastrem.

Wymagania wstępne

Wybierz kartę dla systemu operacyjnego używanego do uruchamiania oprogramowania MATLAB.

  1. Pobierz pakiet Microsoft Identity Client i Microsoft Identity Abstractions z narzędzia NuGet.

  2. Wyodrębnij pobrane pakiety i pliki DLL z biblioteki lib\net45 do wybranego folderu. W tym artykule użyjemy folderu C:\Matlab\DLL.

Wykonywanie uwierzytelniania użytkownika

W przypadku uwierzytelniania użytkownika użytkownik jest monitowany o zalogowanie się za pośrednictwem okna przeglądarki. Po pomyślnym zalogowaniu zostanie przyznany token autoryzacji użytkownika. W tej sekcji pokazano, jak skonfigurować ten interaktywny przepływ logowania.

Aby przeprowadzić uwierzytelnianie użytkownika:

  1. Zdefiniuj stałe wymagane do autoryzacji. Aby uzyskać więcej informacji na temat tych wartości, zobacz Parametry uwierzytelniania.

    % 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. W programie MATLAB Studio załaduj wyodrębnione pliki DLL:

    % 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. Użyj elementu PublicClientApplicationBuilder , aby wyświetlić monit o interakcyjne logowanie użytkownika:

    % 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. Użyj tokenu autoryzacji, aby wysłać zapytanie do klastra za pomocą interfejsu API REST:

    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
    

Wykonywanie uwierzytelniania aplikacji

Microsoft Entra autoryzacja aplikacji może być używana w scenariuszach, w których logowanie interakcyjne nie jest wymagane, a wymagane są automatyczne uruchomienia.

Aby przeprowadzić uwierzytelnianie aplikacji:

  1. Aprowizuj aplikację Microsoft Entra. W polu Identyfikator URI przekierowania wybierz pozycję Sieć Web i dane wejściowe http://localhost:8675 jako identyfikator URI.

  2. Zdefiniuj stałe wymagane do autoryzacji. Aby uzyskać więcej informacji na temat tych wartości, zobacz Parametry uwierzytelniania.

    % 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. W programie MATLAB Studio załaduj wyodrębnione pliki DLL:

     % 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. Użyj klasy ConfidentialClientApplicationBuilder, aby wykonać nieinterakcyjne automatyczne logowanie przy użyciu aplikacji Microsoft Entra:

    %  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. Użyj tokenu autoryzacji, aby wysłać zapytanie do klastra za pomocą interfejsu API REST:

    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