Azure Active Directory Authentication Library (ADAL) for Python

1.2.7 · deprecated · verified Sat Mar 28

ADAL for Python is a legacy library that enabled Python applications to authenticate to Azure Active Directory (AAD) to access AAD-protected web resources. It has been replaced by the Microsoft Authentication Library (MSAL) for Python, which offers broader functionality and support for newer authentication protocols and features. ADAL Python will no longer receive new feature improvements or bug fixes. The current version is 1.2.7.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to acquire an access token using the client credentials flow, where an application authenticates itself using a client ID and client secret to access a protected resource like Microsoft Graph. Ensure you have registered an application in Azure AD and granted it appropriate permissions.

import os
import adal

# Set these environment variables or replace directly for testing
TENANT_ID = os.environ.get('AZURE_TENANT_ID', 'your_tenant_id_here')
CLIENT_ID = os.environ.get('AZURE_CLIENT_ID', 'your_client_id_here')
CLIENT_SECRET = os.environ.get('AZURE_CLIENT_SECRET', 'your_client_secret_here')
RESOURCE = os.environ.get('AZURE_RESOURCE', 'https://graph.microsoft.com') # Example: Microsoft Graph URL

AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"

try:
    # Initialize AuthenticationContext, explicitly setting api_version=None is recommended
    context = adal.AuthenticationContext(
        AUTHORITY,
        validate_authority=True,
        api_version=None
    )

    # Acquire a token using the client credentials flow
    # This flow is for daemon/service applications that authenticate as themselves
    token_response = context.acquire_token_with_client_credentials(
        RESOURCE,
        CLIENT_ID,
        CLIENT_SECRET
    )

    access_token = token_response.get('accessToken')

    if access_token:
        print("Successfully acquired access token.")
        print(f"Access Token (first 20 chars): {access_token[:20]}...")
        # You can now use the access_token to call the protected resource
        # Example: import requests; headers = {'Authorization': 'Bearer ' + access_token}
        # response = requests.get(f'{RESOURCE}/v1.0/users', headers=headers)
        # print(response.json())
    else:
        print("Failed to acquire access token.")
        print(token_response)

except adal.AdalError as e:
    print(f"ADAL Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →