Keycloack: Streamlit Login ultra-powered
But if you have a more complex (micro-frontend/multi-frontend application) web application in which streamlit is only a component you mast need to centralize login.
That can be easy with Keycloack that get you a microservice that manage a full-featured login with realm, roles and more.
We can implement Keycloack login with streamlit trough streamlit-keycloack library.
Create the Streamlit APP
Start from requirements.txt that describe the needed libraries
Write the streamlit app at src/main.py
from dataclasses import asdict
import streamlit as st
from streamlit_keycloak import login
keycloak = login(
"labelButton": "Sign in",
"labelLogin": "Please sign in to your account.",
"errorNoPopup": "Unable to open the authentication popup. Allow popups and refresh the page to proceed.",
"errorPopupClosed": "Authentication popup was closed manually.",
"errorFatal": "Unable to connect to Keycloak using the current configuration."
st.write(f"Here is your user information:")
Now we can configure our Dockerfile to run the streamlit app:
# for streamlit
RUN mkdir -p /root/.streamlit
RUN bash -c 'echo -e "\
email = \"\"\n\
" > /root/.streamlit/credentials.toml'
RUN bash -c 'echo -e "\
enableCORS = false\n\
" > /root/.streamlit/config.toml'
ADD requirements.txt .
RUN pip install --upgrade pip && pip install -r requirements.txt
COPY src ./src
CMD streamlit run src/main.py --server.port 8000 --server.enableCORS=true --server.enableXsrfProtection=false
And docker-compose.yml with streamlit and keycloack service:
network_mode: "host" # importat to see keycloack with the same name and port of the frontend localhost:3333
Now we can run it with
docker-compose up or if you have latest version of docker
docker compose up .
When the services finish their initialization you will see:
Now go to keyclaock and login to admin console with admin, password:
Add a new realm called myrealm and save:
Go to clients and create a new clients that:
Create a user ander User, add user. Click on the created user and set a new password under Credentials tab, if you do not want to change the password at first login remember to put temporary off.
Now you can open the streamlit page and login with the created user credentials.
Actually the library do not include a logout, you must go to keyclock link and press sign out at that link: http://localhost:3333/auth/realms/myrealm/account/.
Streamlit are reaching more and more integration and it can be very usefull tool. Thanks to all the people that relase open source libraries that help us to work quickly and better!
And… good contribution to all!