Streamlit is a fantastic tool for creating data-driven web applications quickly and easily. However, as your apps grow in complexity and reach a wider audience, you'll often need to implement authentication and user management features. In this blog post, we'll explore different approaches to adding these crucial elements to your Streamlit projects.
Let's start with the simplest form of authentication: password protection. This method is suitable for small-scale projects or internal tools where you just need a basic layer of security.
Here's a simple example:
import streamlit as st def check_password(): def password_entered(): if st.session_state["password"] == "supersecret": st.session_state["password_correct"] = True del st.session_state["password"] else: st.session_state["password_correct"] = False if "password_correct" not in st.session_state: st.text_input( "Enter the password", type="password", on_change=password_entered, key="password" ) return False elif not st.session_state["password_correct"]: st.text_input( "Enter the password", type="password", on_change=password_entered, key="password" ) st.error("😕 Password incorrect") return False else: return True if check_password(): st.write("Welcome to the secure area!")
This code creates a simple password-protected area in your Streamlit app. Users must enter the correct password to access the content.
For a more robust solution that persists across sessions, you can implement cookie-based authentication. This approach allows users to stay logged in even after closing and reopening the browser.
Here's a basic implementation using the streamlit_cookies_manager
package:
import streamlit as st from streamlit_cookies_manager import EncryptedCookieManager cookies = EncryptedCookieManager( prefix="myapp/", password='mysecretkey' ) if not cookies.ready(): st.stop() # Check if user is logged in if 'logged_in' not in cookies: cookies['logged_in'] = False if not cookies['logged_in']: username = st.text_input("Username") password = st.text_input("Password", type="password") if st.button("Login"): if username == "admin" and password == "password": cookies['logged_in'] = True cookies['username'] = username st.experimental_rerun() else: st.error("Invalid credentials") else: st.write(f"Welcome back, {cookies['username']}!") if st.button("Logout"): cookies['logged_in'] = False st.experimental_rerun() cookies.save()
This example demonstrates how to use encrypted cookies to maintain user sessions across page reloads and browser restarts.
For more advanced applications, you might want to integrate with external authentication services like Google, Facebook, or GitHub. This approach provides a more secure and feature-rich authentication system.
Here's an example using the streamlit_auth
package to integrate with Google authentication:
import streamlit as st from streamlit_auth import GoogleAuth # Initialize Google Auth auth = GoogleAuth( client_id="your-client-id.apps.googleusercontent.com", client_secret="your-client-secret", redirect_uri="http://localhost:8501", scopes=['openid', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'] ) # Check if user is authenticated if not auth.is_authenticated(): auth.login() else: user_info = auth.get_user_info() st.write(f"Welcome, {user_info['name']}!") st.write(f"Your email: {user_info['email']}") if st.button("Logout"): auth.logout() st.experimental_rerun()
This code snippet demonstrates how to integrate Google authentication into your Streamlit app, allowing users to log in with their Google accounts.
Once you have authentication in place, you'll likely want to implement user management features. This might include:
Here's a simple example of how you might implement user registration and profile management:
import streamlit as st import pandas as pd # Load or create user database @st.cache_data def load_users(): try: return pd.read_csv("users.csv") except FileNotFoundError: return pd.DataFrame(columns=["username", "password", "email"]) users = load_users() def save_users(): users.to_csv("users.csv", index=False) # User registration def register_user(username, password, email): if username in users["username"].values: return False users.loc[len(users)] = [username, password, email] save_users() return True # User login def login_user(username, password): user = users[(users["username"] == username) & (users["password"] == password)] return not user.empty # Streamlit UI if "logged_in" not in st.session_state: st.session_state.logged_in = False if not st.session_state.logged_in: choice = st.radio("Choose an option", ["Login", "Register"]) if choice == "Login": username = st.text_input("Username") password = st.text_input("Password", type="password") if st.button("Login"): if login_user(username, password): st.session_state.logged_in = True st.session_state.username = username st.experimental_rerun() else: st.error("Invalid credentials") else: username = st.text_input("Choose a username") password = st.text_input("Choose a password", type="password") email = st.text_input("Enter your email") if st.button("Register"): if register_user(username, password, email): st.success("Registration successful! Please log in.") else: st.error("Username already exists") else: st.write(f"Welcome, {st.session_state.username}!") if st.button("Logout"): st.session_state.logged_in = False st.experimental_rerun()
This example demonstrates a basic user management system with registration, login, and logout functionality. It uses a CSV file to store user information, but in a real-world application, you'd want to use a more secure database system.
By following these guidelines and implementing robust authentication and user management systems, you can create secure and personalized Streamlit applications that provide a great user experience while protecting sensitive information.
21/09/2024 | Python
26/10/2024 | Python
05/10/2024 | Python
17/11/2024 | Python
15/11/2024 | Python
26/10/2024 | Python
26/10/2024 | Python
06/10/2024 | Python
15/10/2024 | Python
06/10/2024 | Python
06/10/2024 | Python
15/10/2024 | Python