Using Keycloak with Streamlit

Hey guys,

Got anyone a working example of an integration of
authentification with Keyclock into Streamlit?

I am able to authentificate when using login and password. But I do not want to deliver the login form in my application but like to redirect to the keycloak login form and go back to my application if login is correct.

So a access token has to be used. But after reading for hours I haven’t found the part dealing with the redirection to Keyclock and so on.

Every hint and ideas are highly appreciated.

Dirk

Hi Dirk,

I was running into similar issues and came up with the following component: streamlit-keycloak

The component first attempts single sign on silently and if this fails, opens a popup to the keycloak login page. After logging in, authentication state, an oauth token and user info is available in the application.

Hopefully this also works for your use case. Feedback is always welcome.

2 Likes

Hi @bleumink ,

As you know, I try your component and it’s usefull for me :slight_smile:
I wanted to know how do you logout? I tried to add a disconnect button.

I tried some stuff like below without success: Probably because it attempts to sign on silently first.

from dataclasses import asdict
from streamlit_keycloak import login
import streamlit as st


def main():
    st.subheader(f"Welcome {keycloak.user_info['preferred_username']}!")
    st.write(f"Here is your user information:")
    st.write(asdict(keycloak))
    if st.button("Disconnect"):
        keycloak.authenticated = False


st.title("Streamlit Keycloak example")
keycloak = login(
    url="http://localhost:8080",
    realm="myrealm",
    client_id="myclient",
)

if keycloak.authenticated:
    main()

Is there a proper way to logout with your component or the functionnality is not implemented?

Enjoy your day
Bruno

Hi Bruno,

Logging out is currently not implemented. The reasoning behind this is that a large use case for Keycloak is the single sign-on functionality. So signing out from the Streamlit app would also sign you put from all other services. So I reasoned Keycloak users wouldn’t be signing out that much.

It is on my todo list to implement this at some point though and keycloak-js provides functionality for doing this, but it might take a while until I get around to actually doing it.

Gideon

1 Like

Alright, I understand.
Thank you very much for your answer.
Enjoy your day