How to refresh access token for Microsoft Graph in Python
The connection to Microsoft Graph with Flask-OAuthlib described well in this tutorial.
One detail it’s missing - how to refresh the access token, because it expires in an hour.
In Flask-OAuthlib there is no method for this but it can be done easily with a POST
request.
import requests
from flask_oauthlib.client import OAuth
from .config import AZURE_CLIENT_ID, AZURE_CLIENT_SECRET
oauth = OAuth()
microsoft = oauth.remote_app(
'azure',
consumer_key=AZURE_CLIENT_ID,
consumer_secret=AZURE_CLIENT_SECRET,
request_token_params={'scope': ' '.join([
'https://graph.microsoft.com/Group.Read.All',
'https://graph.microsoft.com/User.Read.All',
'offline_access'
])},
base_url='https://graph.microsoft.com/v1.0/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://login.microsoftonline.com/common/oauth2/v2.0/token',
authorize_url='https://login.microsoftonline.com/common/oauth2/v2.0/authorize')
def refresh_credentials(refresh_token):
data = {
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': microsoft.consumer_key,
'client_secret': microsoft.consumer_secret}
response = requests.post(microsoft.access_token_url, data=data)
credentials = response.json()
return credentials