Introduction
Streamlit apps are public by default. The moment you put one on Community Cloud, anyone with the URL can use it. For internal tools, dashboards, or paid products, you need authentication.
This post builds a complete auth flow in Streamlit: login page, session state, protected pages, and logout — no external service required for small apps.
The approach
Streamlit’s st.session_state persists across reruns within a user’s session. We’ll store a logged_in flag and user info there, gate pages behind it, and clear it on logout.
For production, swap the hardcoded check for a real backend (FastAPI + JWT, or an auth provider). The pattern stays the same.
Step 1: Login page
import streamlit as st
st.set_page_config(page_title="Login", page_icon="🔐")
# Simple credential check (replace with real auth in production)
USERS = {"admin": "secret", "galvan": "pass123"}
def login():
st.title("🔐 Login")
with st.form("login_form"):
username = st.text_input("Username")
password = st.text_input("Password", type="password")
submitted = st.form_submit_button("Log in")
if submitted:
if username in USERS and USERS[username] == password:
st.session_state.logged_in = True
st.session_state.username = username
st.rerun()
else:
st.error("Invalid credentials")
if "logged_in" not in st.session_state:
st.session_state.logged_in = False
if not st.session_state.logged_in:
login()
st.stop() # don't render anything below
st.stop() is the key — it halts execution so protected content never renders for logged-out users.
Step 2: Protected content
# After the login gate above, render the app
st.title(f"Welcome, {st.session_state.username}!")
st.write("This content is protected.")
if st.button("Logout"):
st.session_state.logged_in = False
st.session_state.username = None
st.rerun()
Step 3: Multi-page app with auth
Streamlit’s multipage apps use files in a pages/ folder. Gate each page:
# pages/dashboard.py
import streamlit as st
if not st.session_state.get("logged_in"):
st.warning("Please log in first.")
st.stop()
st.title("📊 Dashboard")
st.write("Protected dashboard content here.")
And a shared auth helper:
# auth.py
import streamlit as st
def require_login():
if not st.session_state.get("logged_in"):
st.warning("Please log in to continue.")
st.stop()
def logout():
st.session_state.logged_in = False
st.session_state.username = None
st.rerun()
Import in every page: from auth import require_login; require_login().
Step 4: Remember me (persistent login)
Streamlit sessions reset on tab close. For “remember me”, use a cookie:
pip install extra-streamlit-components
import extra_streamlit_components as stx
cookie_manager = stx.CookieManager()
token = cookie_manager.get(cookie="auth_token")
if token and verify_token(token):
st.session_state.logged_in = True
st.session_state.username = decode_token(token)
Set the cookie on login, clear it on logout. This survives browser restarts.
Step 5: Role-based access
ROLES = {"admin": ["dashboard", "settings", "users"],
"viewer": ["dashboard"]}
def has_access(page):
role = st.session_state.get("role", "viewer")
return page in ROLES.get(role, [])
if not has_access("settings"):
st.error("You don't have access to this page.")
st.stop()
Step 6: Real backend auth (production)
For production, replace the hardcoded USERS dict with a real check:
import requests
def authenticate(username, password):
r = requests.post("https://your-api.com/login",
json={"username": username, "password": password})
if r.status_code == 200:
return r.json()["token"]
return None
Store the JWT in st.session_state.token and pass it as a Bearer header on every API call. See the FastAPI + Streamlit post for the backend.
Auth providers (alternatives)
| Approach | Effort | Best for |
|---|---|---|
| Hardcoded (this post) | Low | Demos, prototypes |
| FastAPI + JWT (your own) | Medium | Full control |
Streamlit’s st.login() (new) |
Low | OAuth (Google, etc.) |
| Auth0 / Clerk / Supabase | Medium | Production SaaS |
streamlit-authenticator lib |
Low | Quick password-based auth |
Streamlit recently added st.login() for OAuth — check the docs if you want Google/GitHub login without building it yourself.
Common mistakes
- Storing passwords in code — fine for demos, never for production. Use a real backend.
- No
st.stop()— without it, protected content renders briefly before the redirect. - Session state across users —
st.session_stateis per-user, but don’t store global secrets in it. - Forgetting logout — always provide a logout button that clears state.
- Trusting client-side state — for sensitive apps, re-verify the token on the backend for every request.
Key Concepts
st.session_state= per-user persistent state across rerunsst.stop()= halt rendering (gate protected content)st.rerun()= force a fresh render after state change- JWT = token-based auth for API calls
- Cookies = persistent login across browser sessions
What to Try Next
- Build a FastAPI backend with real JWT auth.
- Add role-based access to your data dashboard.
- Combine with Streamlit 2026 features (
st.menu_buttonfor a user menu with logout). - Deploy with Streamlit Community Cloud and test the auth flow.
FAQ
Is Streamlit auth secure enough for production?
The pattern here (session state) is fine for internal tools and low-risk apps. For production SaaS with sensitive data, use a real auth provider (Auth0, Clerk, Supabase) or OAuth via st.login(). Never roll your own crypto.
Does st.session_state persist across browser tabs?
No — it’s per-tab/per-session. For cross-tab or persistent login, use cookies (Step 4) or an auth provider.
Can I use Streamlit’s built-in st.login()?
Yes — Streamlit added OAuth support. It handles the redirect flow for Google, GitHub, etc. See the official docs for setup. It’s the easiest path if you want social login.