Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Microsoft Graph using MSAL with Python and Certificate Authentication. Associated blogpost
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 = ''
tenantID = 'yourTenantID'
authority = '' + tenantID
clientID = 'yourAADAppClientID'
scope = ['']
thumbprint = 'yourCertThumbPrint'
certfile = '.\\yourCertFile.pem'
queryUser = ""
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
if not accessToken:
# 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.')
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")
# Token Expiry
tokenExpiry = msal_jwt_expiry(accessToken['access_token'])
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']}
minutesToExpiry = time_to_expiry.seconds / 60
print("Access Token Expires in '" + str(minutesToExpiry) +" minutes'")
except Exception as err:
# Query
if requestHeaders and accessToken:
queryResults = msgraph_request(graphURI + '/beta/users/'+queryUser,requestHeaders)
print(json.dumps(queryResults, indent=2))
except Exception as err:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment