I need to authenticate to Azure AD to perform REST API calls. I'm using Azure Python SDK (https://github.com/Azure/azure-sdk-for-python) for that. I have another code that returns me the JWT (JSON Web Token) of the user. How can I connect with this JWT? I try to look here https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=cmd but I didn't find something useful
1 Answer
To call the REST API secured by azure ad, just make an API call with python, pass the token you got to the request header.
As you don't mention the specific API you want to call, here is just an approximate sample, change the url to the API you want and change requests.get to the method you want, there are maybe other headers and bodies depend on the specific API, the access_token is the token you should pass.
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)
Note: You don't provide the code you got the token, I don't know if it is correct, please make sure the audience of the token is correct and has the permission to call the corresponded API, otherwise you will get an error.
Reference: