Created
October 14, 2024 15:23
-
-
Save mitchellaha/3dda94d0999b81dd710cd4e3928a5105 to your computer and use it in GitHub Desktop.
Microsoft Graph API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
! THIS ACCESS THE GRAPH API WITHOUT A SPECIFIC USER | |
! THIS USES API PERMISSIONS -> APPLICATION PERMISSIONS | |
! | |
""" | |
import json | |
import logging | |
import requests | |
import msal | |
config = { | |
"authority": "https://login.microsoftonline.com/{}", # https://login.microsoftonline.com/{tenant_id} | |
"client_id": "<>", # Application (client) ID of app registration | |
"scope": [ "https://graph.microsoft.com/.default" ], | |
"secret": "<>", # Secret key of app registration | |
"endpoint": "https://graph.microsoft.com/v1.0/users" | |
} | |
# Create a preferably long-lived app instance which maintains a token cache. | |
app = msal.ConfidentialClientApplication( | |
config["client_id"], authority=config["authority"], | |
client_credential=config["secret"], | |
# token_cache=... # Default cache is in memory only. | |
# You can learn how to use SerializableTokenCache from | |
# https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache | |
) | |
# The pattern to acquire a token looks like this. | |
result = None | |
# Firstly, looks up a token from cache | |
# Since we are looking for token for the current app, NOT for an end user, | |
# notice we give account parameter as None. | |
result = app.acquire_token_silent(config["scope"], account=None) | |
if not result: | |
logging.info("No suitable token exists in cache. Let's get a new one from AAD.") | |
result = app.acquire_token_for_client(scopes=config["scope"]) | |
if "access_token" in result: | |
# Calling graph using the access token | |
graph_data = requests.get( # Use token to call downstream service | |
config["endpoint"], | |
headers={'Authorization': 'Bearer ' + result['access_token']}, ).json() | |
print("Graph API call result: ") | |
print(json.dumps(graph_data, indent=2)) | |
else: | |
print(result.get("error")) | |
print(result.get("error_description")) | |
print(result.get("correlation_id")) # You may need this when reporting a bug | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment