pythonazureflaskmicrosoft-entra-idmsal

Fail to get access token from msal python library


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)

Screen Shoot of app registration API Permission

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


Solution

  • To connect with Microsoft Graph API via application, make use of acquire_token_for_client flow.

    I created a Microsoft Entra ID application and granted API permissions:

    enter image description here

    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:

    enter image description here

    When decoded the roles are displayed:

    enter image description here

    Using the above generated access token, you can call Microsoft Graph API.