avatarThe QAE

Summary

This article provides a step-by-step guide on how to authenticate Python applications with Azure Active Directory (Azure AD) using OAuth2 for API testing against Microsoft Dynamics.

Abstract

The article titled "Azure Active Directory And Python: How to Authenticate Using OAuth2 with Examples" is a technical tutorial that guides developers through the process of authenticating Python applications with Azure AD. It outlines the necessary prerequisites, including having the Azure Tenant ID, Client ID, and Client Secret from the App Registration. The article explains the importance of authenticating into Azure AD to access and manage Azure resources. It provides code snippets for importing required libraries, setting up OAuth2 credentials, defining the OAuth2 endpoint, creating an OAuth2 session, fetching the Bearer Token, and testing the connection to Microsoft Dynamics. The author emphasizes the ease of using the requests and requests-oauthlib libraries to facilitate the authentication process and verifies the successful authentication with a 200 response code.

Opinions

  • The author believes that using Azure AD in scripts is particularly useful for API testing against Microsoft Dynamics.
  • The article conveys that the process of authenticating with Azure AD can be straightforward when following the provided steps and using the recommended Python libraries.
  • The author suggests that readers can modify the provided code examples to suit their specific Azure AD Application Registration credentials and API endpoints.
  • The inclusion of a full code example at the end of the article indicates the author's opinion that readers will benefit from a complete, working example to guide their implementation.
  • The author assumes that readers are familiar with Python and have a basic understanding of OAuth2 and API interactions.
  • The article implies that successful authentication is a critical first step before any API interaction with Azure resources.
Photo by Ed Hardie on Unsplash

Azure Active Directory And Python: How to Authenticate Using OAuth2 with Examples

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. Or, jump straight to the code.

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 requests 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 requests 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, that will fetch and store the Bearer Token used to access Dynamics.

At this point our access has been granted and we have successfully authenticated into Azure AD! Next, we will test our connection.

 token = oauth2_session.fetch_token(
            token_url=token_url, 
            client_id=client_id, 
            client_secret=client_secret, 
            resource_url=resource_url)

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 reponse in your console along with a success message. Else, you will see “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.")

Happy testing!

Python
Testing
Software Development
Oauth2
Azure Active Directory
Recommended from ReadMedium