问题描述
我需要对 Azure AD 进行身份验证才能执行 REST API 调用。 为此,我正在使用 Azure Python SDK (https://github.com/Azure/azure-sdk-for-python)。 我有另一个代码可以返回用户的 JWT(JSON Web 令牌)。 我怎样才能连接到这个 JWT? 我试着看看这里https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=cmd 但我没有找到有用的东西
解决方法
要调用 azure ad 保护的 REST API,只需使用 python 进行 API 调用,将获得的令牌传递给请求头。
由于你没有提到你要调用的具体API,这里只是一个大概的例子,把url
改成你想要的API,把requests.get
改成你想要的方法,有可能其他标头和正文取决于特定的 API,access_token
是您应该传递的令牌。
import requests
url = 'https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Network/virtualnetworks?api-version=2015-06-15'
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' + access_token}
response = requests.get(url=url,headers = headers)
print(response.status_code)
print(response.text)
注意:你没有提供你得到token的code,不知道对不对,请确认token的受众是正确的,有权限调用对应的API,否则会报错。
参考: