Authenticating into Azure AD allows your Python applications to access and manage various Azure resources, such as virtual machines, databases, storage, and more.
In testing, one way we can use Azure AD in our scripts is for API testing against Microsoft Dynamics.
In this article, we will provide the code and demonstrate how to connect to Azure AD using Python. We will also test our connection for a 200 response.
Prerequisites
- You have the Azure Tenant ID
- You have the Client ID and Client Secret from the App Registration
- The required packages have been installed. You can install the required packages by running:
pip install requests requests-oauthlib
1. Add the required imports
These request libraries allow us to fetch the access token from the provider.
import requests
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
2. Provide the OAuth2 credentials
Here we provide the credentials we will send in order to fetch the access token. Modify the Client ID, Client Secret, and Resource URL to match your credentials
# Your OAuth2 credentials from the Azure AD Application Registration
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
resource_url = "https://your-dynamics-instance.crm.dynamics.com" # Replace with your Dynamics instance URL
3. Provide the OAuth2 endpoint
This is the URL we use to authenticate. Modify this URL to match your Tenant ID.
token_url = "https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/token" # Replace with your Tenant ID
4. Create an OAuth2 session with client credentials
Here we leverage the request libraries to create the OAuth2 session.
client = BackendApplicationClient(client_id=client_id)
oauth2_session = OAuth2Session(client=client)
5. Fetch and store the Bearer Token
Here we are creating a variable, called token
, which will fetch and store the Bearer Token used to access Dynamics.
token = oauth2_session.fetch_token(
token_url=token_url,
client_id=client_id,
client_secret=client_secret,
resource_url=resource_url)
At this point, our access has been granted and we have successfully authenticated into Azure AD! Next, we will test our connection.
6. Testing our connection: Create an authenticated request to Microsoft Dynamics
Let’s test that a valid Bearer Token was created by sending a request to our Resource URL.
First, we define our headers. Then, provide the endpoint we want to hit. After that, we send our request and store it in the response variable. Finally, we’ll create an If Else to validate the response code.
Defining our headers, providing an endpoint, sending our request, and storing the response:
headers = {
'Authorization': f"{token['access_token']}",
}
api_endpoint = f"{resource_url}" # Replace with the appropriate API endpoint
response = requests.get(api_endpoint, headers=headers) # Sending the request with authorization
We can use the next snippet to test the response. If the response is successful, you will see the response in your console along with a success message. Else, you will see the “Failed to fetch data from the API.”.
if response.status_code == 200:
# Uncomment the next 2 lines to see the actual response
#data = response.json()
#print(data)
print("You have successfully authenticated into Azure AD using Python")
else:
print("Failed to fetch data from the API.")

Full code used to authenticate to Azure AD using OAuth2 in Python
You may need to adjust slightly to fit your framework:
# Import required libraries
import requests
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
# Your OAuth2 credentials from the Azure AD Application Registration
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
resource_url = "https://your-dynamics-instance.crm.dynamics.com" # Replace with your Dynamics instance URL
client = BackendApplicationClient(client_id=client_id)
oauth2_session = OAuth2Session(client=client)
# Creating a variable, called token, that will fetch and store the Bearer Token used to access Dynamics
token = oauth2_session.fetch_token(
token_url=token_url,
client_id=client_id,
client_secret=client_secret,
resource_url=resource_url)
# Defining our headers, providing an endpoint, sending our request, and storing the response
headers = {
'Authorization': f"{token['access_token']}",
}
api_endpoint = f"{resource_url}" # Replace with the appropriate API endpoint
response = requests.get(api_endpoint, headers=headers) # Sending the request with authorization
# Testing the response
if response.status_code == 200:
data = response.json()
print(data)
print("You have successfully authenticated into Azure AD using Python")
else:
print("Failed to fetch data from the API.")
Curious to hear your thoughts! Let’s ensure quality together by sharing your insights.