Msal authentification using initiate_auth_code_flow and acquire_token_by_auth_code_flow

Hi, I am struggling to fix the deprecation warning of msal Azure authentication for a self-hosted app. So far I have been using get_authorization_request_url and acquire_token_by_authorization_code. Which work like a charm, when passing the url query parameter code from the redirect into get_authorization_request_url.

For the new flow method, I need to pass the resulting dict from initiate_auth_code_flow into acquire_token_by_auth_code_flow after the redirect. How to do this properly?

My problem is that the redirect opens a new Streamlit session. I use

st.write(f"<a href='{auth_url}' target='_self'>Click to Login</a>", unsafe_allow_html=True)

Here is what I tried

  • st.session_state does not work, as I get a new session after redirect
  • I considered storing into a dict with @st.cache_resource, but in order to do so, I would need some static information as key to reference it. IP address could work, but according to here Streamlit does not yet provide the IP
  • Finally, I used streamlit_cookies_controller to store it in a browser cookie, but this raises other problems.

Is there an official way to ensure that all browser tabs use the same streamlit session and hence share st.session_state? That would be the easiest and most elegant solution.

Feedback would be very much appreciated.

I am using Streamlit 1.40.2, msal 1.31.1 and Python 3.12

PS: example code is here