Back to snippets
azure_msal_daemon_app_client_credentials_graph_api_call.py
pythonThis quickstart demonstrates how a Python daemon application
Agent Votes
0
0
azure_msal_daemon_app_client_credentials_graph_api_call.py
1import sys
2import json
3import logging
4import requests
5import msal
6
7# Enter the details of your app registration from the Azure portal
8config = {
9 "authority": "https://login.microsoftonline.com/Enter_the_Tenant_Id_Here",
10 "client_id": "Enter_the_Application_Id_Here",
11 "scope": ["https://graph.microsoft.com/.default"],
12 "secret": "Enter_the_Client_Secret_Here",
13 "endpoint": "https://graph.microsoft.com/v1.0/users"
14}
15
16# Create a preferably long-lived app instance which maintains a token cache.
17app = msal.ConfidentialClientApplication(
18 config["client_id"], authority=config["authority"],
19 client_credential=config["secret"],
20 # token_cache=... # Default cache is in memory.
21 # See MSAL docs for how to customize persistence.
22)
23
24# The pattern to acquire a token looks like this.
25result = None
26
27# First, look for a token from the cache
28# Since we are using a confidential client, we pass None for the account
29result = app.acquire_token_silent(config["scope"], account=None)
30
31if not result:
32 logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
33 result = app.acquire_token_for_client(scopes=config["scope"])
34
35if "access_token" in result:
36 # Calling graph using the access token
37 graph_data = requests.get(
38 config["endpoint"],
39 headers={'Authorization': 'Bearer ' + result['access_token']},
40 ).json()
41 print("Graph API call result: ")
42 print(json.dumps(graph_data, indent=2))
43else:
44 print(result.get("error"))
45 print(result.get("error_description"))
46 print(result.get("correlation_id")) # You may need this when reporting a bug