Last active
July 7, 2024 18:10
-
-
Save darrenjrobinson/b22b29b95e004fad068166fd92b68e84 to your computer and use it in GitHub Desktop.
Microsoft Graph using MSAL with Python and Certificate Authentication. Associated blogpost https://blog.darrenjrobinson.com/microsoft-graph-using-msal-with-python-and-certificate-authentication/
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
import msal | |
import jwt | |
import json | |
import sys | |
import requests | |
from datetime import datetime | |
global accessToken | |
global requestHeaders | |
global tokenExpiry | |
accessToken = None | |
requestHeaders = None | |
tokenExpiry = None | |
graphURI = 'https://graph.microsoft.com' | |
tenantID = 'yourTenantID' | |
authority = 'https://login.microsoftonline.com/' + tenantID | |
clientID = 'yourAADAppClientID' | |
scope = ['https://graph.microsoft.com/.default'] | |
thumbprint = 'yourCertThumbPrint' | |
certfile = '.\\yourCertFile.pem' | |
queryUser = "[email protected]" | |
def msal_certificate_auth(clientID, scope, authority, thumbprint, certfile): | |
app = msal.ConfidentialClientApplication(clientID, authority=authority, client_credential={"thumbprint": thumbprint, "private_key": open(certfile).read()}) | |
result = app.acquire_token_for_client(scopes=scope) | |
return result | |
def msgraph_request(resource, requestHeaders): | |
# Request | |
results = requests.get(resource, headers=requestHeaders).json() | |
return results | |
def msal_jwt_expiry(accessToken): | |
decodedAccessToken = jwt.decode(accessToken, verify=False) | |
accessTokenFormatted = json.dumps(decodedAccessToken, indent=2) | |
# Token Expiry | |
tokenExpiry = datetime.fromtimestamp(int(decodedAccessToken['exp'])) | |
print("Token Expires at: " + str(tokenExpiry)) | |
return tokenExpiry | |
# Auth | |
try: | |
if not accessToken: | |
try: | |
# Get a new Access Token using Client Credentials Flow and a Self Signed Certificate | |
accessToken = msal_certificate_auth(clientID, scope, authority, thumbprint, certfile) | |
requestHeaders = { | |
'Authorization': 'Bearer ' + accessToken['access_token']} | |
except Exception as err: | |
print('Error acquiring authorization token. Check your tenantID, clientID and certficate thumbprint.') | |
print(err) | |
if accessToken: | |
# Example of checking token expiry time to expire in the next 10 minutes | |
decodedAccessToken = jwt.decode(accessToken['access_token'], verify=False) | |
accessTokenFormatted = json.dumps(decodedAccessToken, indent=2) | |
print("Decoded Access Token") | |
print(accessTokenFormatted) | |
# Token Expiry | |
tokenExpiry = msal_jwt_expiry(accessToken['access_token']) | |
now = datetime.now() | |
time_to_expiry = tokenExpiry - now | |
if time_to_expiry.seconds < 600: | |
print("Access Token Expiring Soon. Renewing Access Token.") | |
accessToken = msal_certificate_auth(clientID, scope, authority, thumbprint, certfile) | |
requestHeaders = {'Authorization': 'Bearer ' + accessToken['access_token']} | |
else: | |
minutesToExpiry = time_to_expiry.seconds / 60 | |
print("Access Token Expires in '" + str(minutesToExpiry) +" minutes'") | |
except Exception as err: | |
print(err) | |
# Query | |
if requestHeaders and accessToken: | |
queryResults = msgraph_request(graphURI + '/beta/users/'+queryUser,requestHeaders) | |
try: | |
print(json.dumps(queryResults, indent=2)) | |
except Exception as err: | |
print(err) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment