Search code examples
pythonauthenticationazure-active-directoryazure-ad-msalstreamlit

Unable to get Access Token using MSAL with streamlit


Part of my school project is to use streamlit and MSAL to build a simple login page integrate with Azure Entra ID as idenity provider. Currently, I was able to be redirected to a new page for authentication.. but once I done authentication I will get an error message saying: "AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests. Trace ID: b609a4d4-f55d-4d18-ad83-63bc34601e00 Correlation ID: d38d1ddb-438d-4cf7-858e-7edb817836b4".
My streamlit login page is on localhost 8503, i want to redirect to either the same page or 8501.. Can someone help me troubleshoot why am not getting access token

import streamlit as st
from msal import PublicClientApplication

# Initialize MSAL PublicClientApplication
app = PublicClientApplication(
    "<client_id>",
    authority="https://login.microsoftonline.com/<tenant_ID>",
    client_credential=None
    )

# Function to acquire and use token
def acquire_and_use_token():
    result = None

    # Attempt to get token from cache or acquire interactively
    accounts = app.get_accounts()
    if accounts:
        result = app.acquire_token_silent(["User.Read"], account=accounts[0])
    else:
        result = app.acquire_token_interactive(scopes=["<Not_sure_what_to_enter>"], prompt="select_account")

    # Check if token was obtained successfully
    if "access_token" in result:
        st.write("Token acquisition successful!")
        st.write("Access token:", result["access_token"])

    else:
        st.error("Token acquisition failed")
        st.error(result.get("error_description", "No further details"))
    if result and "access_token" in result:
        st.session_state.token = result["access_token"]
# Streamlit app UI
st.title("Azure Entra ID Authentication with MSAL and Streamlit")


if st.button("Login"):
    acquire_and_use_token()
    # Update session state with token
    

# Display token if available
if st.session_state.token:
    st.write("Access token:", st.session_state.token)
st.write(st.session_state)

**Struggled for days, Please help me troubleshoot, I am trying to get the access_token. **


Solution

  • The error usually occurs if you trying to acquire token with interactive flow by adding redirect URI under "Single-page application" platform like this:

    enter image description here

    Initially, I too got same error when I ran your code to acquire token interactively with redirect URI as SPA:

    enter image description here

    To resolve the error, remove the redirect URI under "Single-page application" platform and add it in "Mobile and desktop applications" like this:

    enter image description here

    When I ran the below code to acquire token interactively after above change, I got the response successfully with token like this:

    import streamlit as st
    from msal import PublicClientApplication
    
    # Initialize MSAL PublicClientApplication
    app = PublicClientApplication(
        "appId",
        authority="https://login.microsoftonline.com/tenantId",
        client_credential=None
        )
    
    # Function to acquire and use token
    def acquire_and_use_token():
        result = None
    
        # Attempt to get token from cache or acquire interactively
        accounts = app.get_accounts()
        if accounts:
            result = app.acquire_token_silent(["User.Read"], account=accounts[0])
        else:
            result = app.acquire_token_interactive(scopes=["User.Read"], prompt="select_account")
    
        # Check if token was obtained successfully
        if "access_token" in result:
            st.write("Token acquisition successful!")
            st.write("Access token:", result["access_token"])
    
        else:
            st.error("Token acquisition failed")
            st.error(result.get("error_description", "No further details"))
        if result and "access_token" in result:
            st.session_state.token = result["access_token"]
    # Streamlit app UI
    st.title("Azure Entra ID Authentication with MSAL and Streamlit")
    
    
    if st.button("Login"):
        acquire_and_use_token()
        # Update session state with token
    

    Streamlit app UI:

    enter image description here