from flask import Flask, jsonify, request, send_file
from flask_cors import CORS
import logging
from msal import ConfidentialClientApplication
app = Flask(__name__)
CORS(app)
# app.config['CORS_HEADERS'] = 'Content-Type'
client_id="clientID"
client_secret="secret"
tenant_id="TenantID"
msal_authority = f"https://login.microsoftonline.com/{tenant_id}"
scopes = ['https://graph.microsoft.com/.default']
msal_app = ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority=msal_authority)
result = msal_app.acquire_token_silent(
scopes=scopes,
account=None
)
if not result:
result = msal_app.acquire_token_for_client(scopes=scopes)
if "access_token" is result:
access_token = result['access_token']
else:
raise Exception("No Access Token Found")
print("access token ==================> ", access_token)
i have an app using python to connect with microsoft Graph API but i need access token to do requests. from the code above im still failed to get an access token from msal library. can some one point out what have i done wrong? thanks before
To connect with Microsoft Graph API via application, make use of acquire_token_for_client
flow.
acquire_token_silent
is used to get a token from the cache if it exists. It is used in scenarios where you have an interactive user session and want to silently obtain a new token without prompting the user again.I created a Microsoft Entra ID application and granted API permissions:
Hence, to get the access token modify the code like below:
from flask import Flask, jsonify, request
#from flask_cors import CORS
import logging
from msal import ConfidentialClientApplication
app = Flask(__name__)
#CORS(app)
client_id="ClientID"
client_secret="ClientSecret"
tenant_id="TenantID"
msal_authority = f"https://login.microsoftonline.com/{tenant_id}"
scopes = ['https://graph.microsoft.com/.default']
msal_app = ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority=msal_authority
)
result = msal_app.acquire_token_for_client(scopes=scopes)
if "access_token" in result:
access_token = result['access_token']
print("Access token ==================> ", access_token)
else:
raise Exception("No Access Token Found: " + result.get("error_description", "Unknown error"))
Access token retrieved successfully:
When decoded the roles are displayed:
Using the above generated access token, you can call Microsoft Graph API.