I have built a web app using Python Dash package and deployed this app on Azure App Service. The web app is currently authenticated through the Azure Portal’s app service authenticate using Microsoft Identity Provider. But how do I get the signed in user details? And how do I authenticate my web app when running locally?
My current sign-in flow is also auto redirect so there is no sign in page and no logout button/option.
I wish to get signed in user details and this is what I have implemented so far:
authentication.py
import msal
import requests
authority = 'https://login.microsoftonline.com/<tenant-id>'
scope = ["https://graph.microsoft.com/.default"]
client_id = <client-id>
client_secret = <client-secret>
def authentication():
app = msal.ConfidentialClientApplication(
client_id,
authority=authority,
client_credential=client_secret
)
token_response = app.acquire_token_for_client(scopes=scope)
access_token = token_response['access_token']
headers = {
'Authorization': f'Bearer {access_token}'
}
response = requests.get(
'https://graph.microsoft.com/v1.0/me', headers=headers)
user_data = response.json()
print("~~~~~~~~~~~~~~~~~~~~~~")
for key, value in user_data.items():
print(f'{key}: {value}')
print("~~~~~~~~~~~~~~~~~~~~~~")
return
And this is my app.py where I called the authentication function:
from functions.app import authentication
# other imports ...
stylesheets = [
"https://unpkg.com/@mantine/dates@7/styles.css",
"https://unpkg.com/@mantine/code-highlight@7/styles.css",
"https://unpkg.com/@mantine/charts@7/styles.css",
"https://unpkg.com/@mantine/carousel@7/styles.css",
"https://unpkg.com/@mantine/notifications@7/styles.css",
"https://unpkg.com/@mantine/nprogress@7/styles.css",
]
app = Dash(__name__, use_pages=True, external_stylesheets=stylesheets)
server = app.server
authentication.authentication()
app.layout = dmc.MantineProvider(
... # layout stuff
)
if __name__ == '__main__':
app.run_server(debug=True, port=8000)
But this is what I am getting when I run my python dash web app (python ./app.py):
{'error': {'code': 'BadRequest', 'message': '/me request is only valid with delegated authentication flow.', 'innerError': {'date': '2024-08-05T03:46:12', 'request-id': '<request-id>', 'client-request-id': '<client-request-id>'}}}