this code uses a service principal in AAD to receive a bearer token which can then be used with msgraph
The correct permissions are required for the graph call
import requests
tenant_id = 'insert tenant id'
client_id = 'insert client id'
client_secret = 'insert client secret'
def get_graph_token():
auth_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
payload = f'grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}&scope=https%3A//graph.microsoft.com/.default'
response = requests.request('POST', auth_url, data = payload)
return response.json()['access_token']
token = get_graph_token()
print(token)