Tutorial on Setting up MS Graph API

#1
by awacke1 - opened
Owner
β€’
edited Oct 9

This is a short tutorial for how to Integrate MS Graph API with your python app.

We will cover..

  1. Azure Web App Registration calling redirect URL
  2. Enable Scope of MS Graph API Permissions for Services you want.
  3. Install Azure Python client package
  4. Auth with authorization code, login not required, for personal use.
  5. Auth with prompt login.

1. Create an Azure App Registration for Web.

image.png for localhost 8000 port and callback method

https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/Authentication/appId/d36c689d-3c61-4be6-a230-c09fc54cf80d/objectId/ece93996-1d7c-4b39-abc5-de51487073ed/isMSAApp~/false/defaultBlade/Overview/appSignInAudience/AzureADandPersonalMicrosoftAccount/servicePrincipalCreated~/true

2. Python in VSCode or Huggingface streamlit app for simplicity:

New streamlit app on Huggingface, then new file App.py
Contents:

APPLICATION_ID=''
CLIENT_SECRET=''

3. Get the Azure Application Client ID from the App Reg:

https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/Overview/appId/d36c689d-3c61-4be6-a230-c09fc54cf80d/objectId/ece93996-1d7c-4b39-abc5-de51487073ed/isMSAApp~/false/defaultBlade/Overview/appSignInAudience/AzureADandPersonalMicrosoftAccount/servicePrincipalCreated~/true

Application Client ID is what you need. Copy and Paste into APPLICATION_ID in py code.

4. Create an Azure secret in MS Graph API Certificates and Secrets

image.png

image.png

5. Copy Azure Value for MSGraphAPI into CLIENT_SECRET py

In Huggingface and Docker you will want to feature your keys outside of the app.py. To do this on Huggingface add both Application ID and and Client secret into Space Secrets which are stored securely in github as secrets, then access them like this:
HF_KEY = os.getenv('HF_KEY')

SO we now will have the first two lines of python to access MS Graph API:

APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')

These will read the Secrets from the Space when it starts up and add them to environment variables for access by py code:

image.png

6. Use Graph Explorer to Test out the API for MS Graph API

https://developer.microsoft.com/en-us/graph/graph-explorer
Log into a MS account that has an Email associated to it. I will use mine AaronCWacker@gmail.com
image.png

7. Test the graph endpoint. Also Determine which endpoints you will want to use.

https://graph.microsoft.com/v1.0/me

{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"@microsoft.graph.tips": "Use $select to choose only the properties your app needs, as this can lead to performance improvements. For example: GET me?$select=signInActivity,accountEnabled",
"userPrincipalName": "AaronCWacker@gmail.com",
"id": "283fb506ed9f3ddf",
"displayName": "Aaron Wacker",
"surname": "Wacker",
"givenName": "Aaron",
"preferredLanguage": "en-US",
"mail": null,
"mobilePhone": null,
"jobTitle": null,
"officeLocation": null,
"businessPhones": []
}

8. Selecting MS Graph Endpoints:

There are the following main options. In ⭐ the main ones we will use for email and scheduling.

Main MSGraph Options

  1. πŸ“‡ Contact -------------- ⭐
  2. πŸ“ Files
  3. πŸ‘₯ Groups
  4. πŸ‘€ Users
  5. πŸ§‘β€πŸ€β€πŸ§‘ Teams
  6. πŸ“± Devices
  7. πŸ“… Meetings -------------- ⭐
  8. βš™οΈ Settings
  9. βœ‰οΈ Mail -------------- ⭐
  10. πŸ›‘οΈ Security -------------- ⭐
  11. πŸ”‘ Access -------------- ⭐
  12. πŸ—“οΈ Calendar -------------- ⭐
  13. πŸ“Š Insights

9. Set Scope of API permissions

image.png

Add a permission
Choose Microsoft Graph, Delegated permissions
To keep things simple first pass through choose my profile endpoint which is shown above (me)

10. Create requirements.txt for python libraries to pull in.

For any python libraries you use pip install -r requirements.txt is used to install all libraries with compatible versions.
You can also use search to review the pypi page for any given python library. This is a great way to get the context and review documentation and code samples for usage of any python library.
For AI Pair Programming a Pro Skill is to be able to copy the appropriate code samples into an AI pipeline (GPT or Claude recommended due to coding python accuracy).

image.png

Create requirements.txt in HF by File, New File then enter msal library and commit:

image.png

You will then have two files in your project:

app.py

import msal
from msal import PublicClientApplication

APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')

requirements.txt

msal

11. Set your graph URL

base_url = 'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'

12. Request API Permissions to create Scope:

image.png

SCOPES = ['User.Read','User.Export.All']

13. Add authority URL used to authenticate:

authority_url = 'https://login.microsoftonline.com/consumers'

14. add client instance method call on msal:

import msal
from msal import PublicClientApplication

APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')

authority_url = 'https://login.microsoftonline.com/consumers'
base_url =  'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'

SCOPES = ['User.Read','User.Export.All']

# Authenticate with Auth Code
client_instance = msal.ConfidentialClientApplication(client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority_url=authority_url )

#15. Get your token from Azure platform - Graph Explorer, Service of User/me and then Access token:

image.png

16. From MS Graph we also need the Response headers

{
    "client-request-id": "72fdf4e2-0ab3-a835-abf6-bbe03077181f",
    "content-type": "application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8",
    "request-id": "5ed61711-f89b-460b-8816-cc0a71181fb3"
}
  1. Use client_instance.get_authorization_request_url

Code should be as follows:

import msal
import os
import streamlit as st

from msal import PublicClientApplication

APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')

authority_url = 'https://login.microsoftonline.com/consumers'
base_url =  'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'

SCOPES = ['User.Read','User.Export.All']

# Authenticate with Auth Code
client_instance = msal.ConfidentialClientApplication(
    client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority=authority_url
)

authorization_request_url = client_instance.get_authorization_request_url(SCOPES)
st.write('Connecting to MSGraph with url:' + authorization_request_url)
webbrowser.open(authorization_request_url, new=True)
  1. Add webbrowser call:
import msal
import os
import streamlit as st
import webbrowser


from msal import PublicClientApplication

APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY ')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY ')

authority_url = 'https://login.microsoftonline.com/consumers'
base_url =  'https://graph.microsoft.com/v1.0/'
endpoint = base_url + 'me'

SCOPES = ['User.Read','User.Export.All']

# Authenticate with Auth Code
client_instance = msal.ConfidentialClientApplication(
    client_id=APPLICATION_ID_KEY, client_credential=CLIENT_SECRET_KEY, authority=authority_url
)

authorization_request_url = client_instance.get_authorization_request_url(SCOPES)
st.write('Connecting to MSGraph with url:' + authorization_request_url)
webbrowser.open(authorization_request_url, new=True)
  1. Since we configured to debug locally when we deploy to HF we need to update the Redirect URI in Azure App Registration.

After entering your deploy URL that you run your app from, delete the localhost entry:

image.png

Sign up or log in to comment