如何使用Python中的Rest API对Azure数据目录进行身份验证并从中获取目录

时间:2019-02-23 01:03:26

标签: python azure azure-data-catalog

我想使用API​​从Azure数据目录中获取目录的名称。当我尝试使用以下命令从Azure数据目录获取目录

requests.get("https://management.azure.com/subscriptions/{id}/resourceGroups/{group_name}/providers/Microsoft.DataCatalog/catalogs/{catalogname}")

如链接https://docs.microsoft.com/en-us/rest/api/datacatalog/data-catalog-data-catalog

中所述

它引发以下错误

响应[400]

好像我必须先进行身份验证。在获取目录之前如何进行身份验证?

2 个答案:

答案 0 :(得分:1)

要调用数据目录REST操作,请创建AuthenticationContext实例并调用AcquireToken。 AuthenticationContext是Active Directory身份验证库NuGet包的一部分。要在Visual Studio中安装Active Directory身份验证库NuGet包,请运行

    #include <iostream>
    #include <fstream>
    #include <stdio.h>
    #include <cstdlib>
    #include <string>
    #include <iomanip>
    #include <fstream>
    using namespace std;
    //int calculatorMin(string fileName);
    //void displayInfo(double mean, int main);
    string getFileInfo();
    double calculateMean (string fileName);

    // main    
    int main ()
    {
    string filename = getFileInfo(); // getting file name 
    double mean = calculateMean( filename); // avg
    return 0;
    }
    // function for getting file 
    string getFileInfo() {
        string filename;
        ifstream inputFile;

        cout << "Please enter a file name to read from: ";
        cin >> filename;

       inputFile.open(filename);

       if (inputFile)
       {
           inputFile.close();
       }

       else
       {
        cout << "Error: Please enter a file name to read from: ";
        cin >> filename;
       }
        //if it opens then name is good and close file then return name
        //if it didn't open, ask for a new name.
        return filename;
    }

    // funtion for mean 
    double calculateMean(string fileName) 
    {
        ifstream infile;
        float num=0;
        float total = 0.0;
        int count = 0;
        infile.open(fileName);
        // While infile successfully extracted numbers from the stream
        while(infile >> num) {
            total += num;
            ++count;
        }
        // don't need the file anymore, close it
        infile.close();
           cout << "The mean was " << total/count << endl;
        // give the average
       return total/count;

    }

从NuGet程序包管理器控制台。

这是获取相同令牌的代码。

 "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" 

这是获取基于id的数据资产的示例代码

static async Task<AuthenticationResult> AccessToken()
        {
            if (authResult == null)
            {
                //Resource Uri for Data Catalog API
                string resourceUri = "https://api.azuredatacatalog.com";

                //To learn how to register a client app and get a Client ID, see https://msdn.microsoft.com/en-us/library/azure/mt403303.aspx#clientID   
                string clientId = clientIDFromAzureAppRegistration;

                //A redirect uri gives AAD more details about the specific application that it will authenticate.
                //Since a client app does not have an external service to redirect to, this Uri is the standard placeholder for a client app.
                string redirectUri = "https://login.live.com/oauth20_desktop.srf";

                // Create an instance of AuthenticationContext to acquire an Azure access token
                // OAuth2 authority Uri
                string authorityUri = "https://login.windows.net/common/oauth2/authorize";
                AuthenticationContext authContext = new AuthenticationContext(authorityUri);

                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                //  AcquireToken takes a Client Id that Azure AD creates when you register your client app.
                authResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always));
            }

            return authResult;
        }

在这里,您可以设置请求,令牌并获得响应。

// The Get Data Asset operation retrieves data asset by Id
        static JObject GetDataAsset(string assetUrl)
        {
            string fullUri = string.Format("{0}?api-version=2016-03-30", assetUrl);

            //Create a GET WebRequest as a Json content type
            HttpWebRequest request = WebRequest.Create(fullUri) as HttpWebRequest;
            request.KeepAlive = true;
            request.Method = "GET";
            request.Accept = "application/json;adc.metadata=full";

            try
            {
                var response = SetRequestAndGetResponse(request);
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var itemPayload = reader.ReadToEnd();
                    Console.WriteLine(itemPayload);
                    return JObject.Parse(itemPayload);
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Status);
                if (ex.Response != null)
                {
                    // can use ex.Response.Status, .StatusDescription
                    if (ex.Response.ContentLength != 0)
                    {
                        using (var stream = ex.Response.GetResponseStream())
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                Console.WriteLine(reader.ReadToEnd());
                            }
                        }
                    }
                }
            }

            return null;
        }

基本上,您需要获取Bearer令牌并将其作为请求参数传递,以便使用Azure数据目录api获得目录。

有关更多代码示例,请浏览下面的代码库。

https://github.com/Azure-Samples/data-catalog-dotnet-get-started

希望有帮助。

答案 1 :(得分:1)

在python中添加新答案

要在python中获取身份验证上下文,您可以执行以下操作

这是调用图api时所需的参数设置。

RESOURCE = "https://graph.microsoft.com"  # Add the resource you want the access token for
TENANT = "Your tenant"  # Enter tenant name, e.g. contoso.onmicrosoft.com
AUTHORITY_HOST_URL = "https://login.microsoftonline.com"
CLIENT_ID = "Your client id "  # copy the Application ID of your app from your Azure portal
CLIENT_SECRET = "Your client secret"  # copy the value of key you generated when setting up the application

# These settings are for the Microsoft Graph API Call
API_VERSION = 'v1.0'

这是登录代码

AUTHORITY_URL = config.AUTHORITY_HOST_URL + '/' + config.TENANT
REDIRECT_URI = 'http://localhost:{}/getAToken'.format(PORT)
TEMPLATE_AUTHZ_URL = ('https://login.microsoftonline.com/{}/oauth2/authorize?' +
                      'response_type=code&client_id={}&redirect_uri={}&' +
                      'state={}&resource={}')
                   

 def login():
    auth_state = str(uuid.uuid4())
    flask.session['state'] = auth_state
    authorization_url = TEMPLATE_AUTHZ_URL.format(
        config.TENANT,
        config.CLIENT_ID,
        REDIRECT_URI,
        auth_state,
        config.RESOURCE)
    resp = flask.Response(status=307)
    resp.headers['location'] = authorization_url
    return resp

这是获取令牌的方式

 auth_context = adal.AuthenticationContext(AUTHORITY_URL)
    token_response = auth_context.acquire_token_with_authorization_code(code, REDIRECT_URI, config.RESOURCE,
                                                                        config.CLIENT_ID, config.CLIENT_SECRET)

,然后可以为您的azure数据目录api创建一个端点。这是相同的http标头-

http_headers = {'Authorization': 'Bearer ' + token_response['accessToken'],
                    'User-Agent': 'adal-python-sample',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'client-request-id': str(uuid.uuid4())}

,最后您可以调用api。这里的端点是数据目录API URL。

data = requests.get(endpoint, headers=http_headers, stream=False).json()

希望有帮助。