Python https请求使用azure AAD身份验证令牌。或CreateAuthorizationHeader()的python版本

2024-09-24 06:33:57 发布

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

谢谢你的帮助。你知道吗

我正在尝试使用python进行API调用。遗憾的是,API的唯一文档是C#中已经存在的一个实现。你知道吗

我的问题是,在我获得一个azureaadtokencredential对象之后,我根本不知道如何在我的HTTPS请求中使用它。你知道吗

def get_data_from_api(credentials):
        serialNumber = "123456789"
        fromDate = "01/10/2019 00:00:00" # DD/m/YYYY HH:MM:SS
        untilDate = "09/10/2019 00:00:00" # DD/m/YYYY HH:MM:SS

        PARAMS = {
            serialNumber: serialNumber,
            fromDate: fromDate,
            untilDate: untilDate
        }
        url = "https://myapi.azurewebsites.net/api/sensordata/GetBySerialNumber"
        r = requests.get(url = url, header={"Authorization": credentials}, params=PARAMS)
        print(r)
        #data = r.json()
        return data

凭据是一个msrestazure.azure\u活动目录.AADTokenCredentials使用adal包检索。 上面的代码导致一个错误,因为header对象只能是字符串。 我的问题是-如何以正确的方式传递授权对象?你知道吗

C#实现如下所示:

            // Make a request to get the token from AAD
            AuthenticationResult result = Task.Run(async () => await authContext.AcquireTokenAsync(resource, cc)).Result;

            // Get the auth header which includes the token from the result
            string authHeader = result.CreateAuthorizationHeader();

            // ...

            // Prepare a HTTP request for getting data.
            // First create a client
            HttpClient client = new HttpClient();

            // Create the actual request. It is a GET request so pass the arguments in the url is enough
            HttpRequestMessage request = new HttpRequestMessage(
            HttpMethod.Get, $"https://api.azurewebsites.net/api/sensordata/GetBySerialNumber?serialNumber={serialNumber}&from={fromDate}&until={untilDate}");

            // Add the required authorization header that includes the token. Without it the request will fail as unauthorized
            request.Headers.TryAddWithoutValidation("Authorization", authHeader);

            // Prepare the response object
            HttpResponseMessage response = Task.Run(async () => await client.SendAsync(request)).Result;



Tags: the对象fromclienttokenapiurldata
1条回答
网友
1楼 · 发布于 2024-09-24 06:33:57

所以是的!我终于解决了。你知道吗

我的问题是,我正在将ADAL对象传递到requests阶段,但是我需要做的是传递使用:'credentials = context.acquire_token_with_client_credentials(resource_uri,client_id,client_secret)'检索的实际令牌。你知道吗

这里,凭据是一个字典,请求头中的身份验证需要:

header = {
    "Authorization": "Bearer "+credentials["accessToken"]
}

r = requests.get(url=url, headers=header, params=PARAMS)

把这个传给请求。获取方法成功了!你知道吗

相关问题 更多 >