0

我想使用 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]

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

4

2 回答 2

2

在 python 中添加新的答案

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

这是调用graph 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()

希望能帮助到你。

于 2019-02-25T05:57:18.603 回答
1

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

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

从 NuGet 包管理器控制台。

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

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;
        }

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

// 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;
        }

以下是设置请求、令牌和获取响应的方法。

  static HttpWebResponse SetRequestAndGetResponse(HttpWebRequest request, string payload = null)
        {
            while (true)
            {
                //To authorize the operation call, you need an access token which is part of the Authorization header
                request.Headers.Add("Authorization", AccessToken().Result.CreateAuthorizationHeader());
                //Set to false to be able to intercept redirects
                request.AllowAutoRedirect = false;

                if (!string.IsNullOrEmpty(payload))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(payload);
                    request.ContentLength = byteArray.Length;
                    request.ContentType = "application/json";
                    //Write JSON byte[] into a Stream
                    request.GetRequestStream().Write(byteArray, 0, byteArray.Length);
                }
                else
                {
                    request.ContentLength = 0;
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                // Requests to **Azure Data Catalog (ADC)** may return an HTTP 302 response to indicate
                // redirection to a different endpoint. In response to a 302, the caller must re-issue
                // the request to the URL specified by the Location response header. 
                if (response.StatusCode == HttpStatusCode.Redirect)
                {
                    string redirectedUrl = response.Headers["Location"];
                    HttpWebRequest nextRequest = WebRequest.Create(redirectedUrl) as HttpWebRequest;
                    nextRequest.Method = request.Method;
                    request = nextRequest;
                }
                else
                {
                    return response;
                }
            }
        }

基本上,您需要获取不记名令牌并将其作为请求参数传递,以使用 azure 数据目录 api 获取目录。

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

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

希望能帮助到你。

于 2019-02-25T05:11:57.320 回答