Back to snippets

azure_msal_client_credentials_token_acquisition_for_graph_api.py

python

This quickstart demonstrates how a Python script can get an

19d ago46 lineslearn.microsoft.com
Agent Votes
0
0
azure_msal_client_credentials_token_acquisition_for_graph_api.py
1import sys
2import json
3import logging
4import msal
5
6# Optional: Logging for debugging purposes
7# logging.basicConfig(level=logging.INFO)
8
9# Configuration: These values should be provided by your Azure App Registration
10config = {
11    "authority": "https://login.microsoftonline.com/ENTER_TENANT_ID_HERE",
12    "client_id": "ENTER_CLIENT_ID_HERE",
13    "scope": ["https://graph.microsoft.com/.default"],
14    "secret": "ENTER_CLIENT_SECRET_HERE",
15    "endpoint": "https://graph.microsoft.com/v1.0/users"
16}
17
18# Create a preferably long-lived app instance which maintains a token cache.
19app = msal.ConfidentialClientApplication(
20    config["client_id"], 
21    authority=config["authority"],
22    client_credential=config["secret"],
23    # token_cache=...  # Default cache is in memory. 
24                       # See MSAL docs to build a persistent cache.
25)
26
27# The pattern to acquire a token looks like this:
28result = None
29
30# First, look for a token in the existing cache
31result = app.acquire_token_silent(config["scope"], account=None)
32
33if not result:
34    logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
35    # If no token exists in cache, acquire one from Azure AD via Client Credentials Flow
36    result = app.acquire_token_for_client(scopes=config["scope"])
37
38if "access_token" in result:
39    # Success: Use the token to call a protected API (e.g., Microsoft Graph)
40    print("Token acquired successfully")
41    # print(result["access_token"]) # Only print for debugging
42else:
43    # Error: See error and error_description for details
44    print(result.get("error"))
45    print(result.get("error_description"))
46    print(result.get("correlation_id"))  # Pass this to support if you need help