Hey there, fellow dev! Ready to dive into the world of Azure Active Directory (Azure AD) integration? You're in the right place. We'll be using the msal
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get msal
installed:
pip install msal
Easy peasy, right?
Now, let's set up our Azure AD creds. Grab your application ID, tenant ID, and client secret from the Azure portal. We'll use these to configure our app:
import msal config = { "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "authority": "https://login.microsoftonline.com/YOUR_TENANT_ID", "scope": ["https://graph.microsoft.com/.default"] }
Time to authenticate! We'll use ConfidentialClientApplication
for this:
app = msal.ConfidentialClientApplication( config["client_id"], authority=config["authority"], client_credential=config["client_secret"] ) result = app.acquire_token_silent(config["scope"], account=None) if not result: result = app.acquire_token_for_client(scopes=config["scope"]) if "access_token" in result: access_token = result["access_token"] else: print(f"Error: {result.get('error')}") print(f"Error description: {result.get('error_description')}")
Now that we've got our token, let's make some API calls:
import requests headers = {'Authorization': 'Bearer ' + access_token} graph_data = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers).json() print(graph_data)
msal
handles token caching for us automatically. To refresh an expired token, just call acquire_token_silent()
again. If it fails, fall back to acquire_token_for_client()
.
Always be prepared for errors. Here's a quick way to handle common ones:
if "error" in result: if result["error"] == "invalid_grant": print("The provided grant has expired. Please re-authenticate.") elif result["error"] == "invalid_client": print("Invalid client secret provided.") else: print(f"An error occurred: {result['error_description']}")
And there you have it! You've just built an Azure AD API integration in Python. Pretty cool, huh? Remember, this is just the beginning. There's a whole world of Azure AD features to explore. Keep coding, keep learning, and most importantly, have fun!
For more info, check out the msal Python docs and the Microsoft Graph API documentation.
Now go forth and integrate!