Get Active Directory authentification data

Yeah I did find a solution to read the user email from the http headers:

import streamlit as st
from streamlit.script_run_context import get_script_run_ctx
from streamlit.server.server import Server

def read_aad_username():
    session_id = get_script_run_ctx().session_id
    session_info = Server.get_current()._get_session_info(session_id)
    headers = session_info.ws.request.headers

    headers = headers._dict

    if "X-Ms-Client-Principal-Name" in headers:
        username = headers["X-Ms-Client-Principal-Name"]
        st.write(f"Logged in as {username}")
    else:
        st.warning(f"could not directly read username from azure active directory.")
        username = None
    return username

If you need more info about the user then you have to send a query to the “/.auth/me” endpoint with the auth-token in the http header. You will also have to give your apps’ service principal the necessary rights to read that data about the user.
However, if you are running a Linux WebApp in azure, be aware of a current bug in active directory which makes it necessary for users to delete browser cookies after a restart: Restarting Azure App Service on Linux with Azure Active Directory authentication resets /.auth/me/

import streamlit as st
from streamlit_javascript import st_javascript

def read_aad_username():
    js_code = """(await fetch("/.auth/me")
    .then(function(response) {return response.json();}).then(function(body) {return body;}))
    """

    return_value = st_javascript(js_code)

    username = None
    if return_value == 0:
        pass # this is the result before the actual value is returned 
    elif isinstance(return_value, list) and len(return_value) > 0:
        username = return_value[0]["user_id"]
        st.write(f"Logged in as {username}")
    else:
        st.warning(f"could not directly read username from azure active directory: {return_value}.")
        st.warning(f"A workaround to this is to clear your browser cookies for this site and reloading it.")
    return username

But that is only needed if you need to know more than just the user email address in which case the first version is enough.

1 Like