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

2024-05-19 22:10:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 数据https命令目录名称comapidata
2条回答

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

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

从NuGet包管理器控制台。在

下面是获取相同令牌的代码。在

和13;

和13;

下面是获取基于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; }

和13;
和13;

下面是如何设置请求、令牌和获取响应。在

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

和13;
和13;

基本上,您需要获取承载令牌并将其作为请求参数传递,以使用azuredatacatalogapi获取目录。在

有关进一步的代码示例,请浏览下面的代码库。在

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

希望有帮助。在

在python中添加新答案

为了在python中获取auth上下文,可以执行以下操作

下面是调用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'

和13;
和13;

这是登录的代码

和13;

和13;
 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()

希望有帮助。在

相关问题 更多 >

编程相关推荐