- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.50.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
user-auth.md docs/
1# User and Authentication23User authentication, login/logout functionality, and user information access. Streamlit provides built-in authentication capabilities for securing applications and managing user sessions.45## Capabilities67### User Information89Access current user information and profile data.1011```python { .api }12user: UserInfoProxy13```1415The user object provides access to authenticated user information including profile data, authentication status, and user attributes.1617Example usage:18```python19# Check if user is authenticated20if st.user.is_authenticated:21st.write(f"Welcome, {st.user.email}!")22st.write(f"User ID: {st.user.id}")2324# Access user profile25if hasattr(st.user, 'name'):26st.write(f"Name: {st.user.name}")2728# Check user permissions29if st.user.has_permission('admin'):30st.write("Admin access granted")31else:32st.write("Please log in to continue")33```3435### Authentication Functions3637Functions for managing user authentication flow.3839```python { .api }40def login(provider, *, oauth2=None):41"""42Initiate user login process with specified authentication provider.4344Args:45provider (str): Authentication provider name46oauth2 (dict, optional): OAuth2 configuration parameters4748Returns:49bool: True if login was successful50"""5152def logout():53"""54Log out the current user and clear authentication state.5556Returns:57bool: True if logout was successful58"""59```6061Example usage:62```python63# Login with different providers64if not st.user.is_authenticated:65col1, col2, col3 = st.columns(3)6667with col1:68if st.button("Login with Google"):69st.login("google")7071with col2:72if st.button("Login with GitHub"):73st.login("github")7475with col3:76if st.button("Login with Microsoft"):77st.login("microsoft")78else:79# User is authenticated80st.success(f"Logged in as {st.user.email}")8182if st.button("Logout"):83st.logout()84st.rerun()8586# Custom OAuth2 configuration87if st.button("Login with Custom Provider"):88oauth_config = {89"client_id": st.secrets["oauth_client_id"],90"client_secret": st.secrets["oauth_client_secret"],91"redirect_uri": "https://myapp.streamlit.app/auth/callback"92}93st.login("custom", oauth2=oauth_config)94```9596### Legacy User Information (Deprecated)9798Deprecated user information interface maintained for backward compatibility.99100```python { .api }101experimental_user: DeprecatedUserInfoProxy102```103104Example usage:105```python106# Deprecated - use st.user instead107if st.experimental_user.email:108st.write(f"User: {st.experimental_user.email}")109```110111### Authentication Patterns112113#### Basic Authentication Flow114115```python116def show_login_page():117"""Display login page with provider options."""118st.title("Welcome")119st.write("Please log in to access the application")120121# Provider selection122provider = st.selectbox(123"Choose login method:",124["google", "github", "microsoft", "azure"]125)126127if st.button(f"Login with {provider.title()}"):128success = st.login(provider)129if success:130st.success("Login successful!")131st.rerun()132else:133st.error("Login failed. Please try again.")134135def show_authenticated_app():136"""Display main application for authenticated users."""137# Header with user info and logout138col1, col2 = st.columns([3, 1])139with col1:140st.title("My Dashboard")141with col2:142st.write(f"👤 {st.user.email}")143if st.button("Logout"):144st.logout()145st.rerun()146147# Main application content148st.write("Welcome to your dashboard!")149# ... rest of app150151# Main app logic152if st.user.is_authenticated:153show_authenticated_app()154else:155show_login_page()156```157158#### Role-Based Access Control159160```python161def check_user_role():162"""Check user role and permissions."""163if not st.user.is_authenticated:164return None165166# Get user role from profile or database167user_role = getattr(st.user, 'role', 'user')168return user_role169170def require_role(required_role):171"""Decorator to require specific user role."""172def decorator(func):173def wrapper(*args, **kwargs):174current_role = check_user_role()175if current_role != required_role:176st.error(f"Access denied. {required_role.title()} role required.")177st.stop()178return func(*args, **kwargs)179return wrapper180return decorator181182@require_role('admin')183def show_admin_panel():184"""Admin-only functionality."""185st.title("Admin Panel")186st.write("Admin controls here")187188# Usage189user_role = check_user_role()190191if user_role == 'admin':192show_admin_panel()193elif user_role == 'user':194st.title("User Dashboard")195st.write("User content here")196else:197st.error("Please log in to continue")198st.stop()199```200201#### Session-Based User Management202203```python204def initialize_user_session():205"""Initialize user session state."""206if "user_initialized" not in st.session_state:207st.session_state.user_initialized = True208209if st.user.is_authenticated:210# Load user preferences211st.session_state.user_preferences = load_user_preferences(st.user.id)212st.session_state.user_data = load_user_data(st.user.id)213214def save_user_preferences():215"""Save current user preferences."""216if st.user.is_authenticated:217save_preferences_to_db(st.user.id, st.session_state.user_preferences)218219# Initialize on app start220initialize_user_session()221222# User-specific functionality223if st.user.is_authenticated:224# Display personalized content225st.title(f"Welcome back, {getattr(st.user, 'name', st.user.email)}!")226227# User preferences228with st.expander("Preferences"):229theme = st.selectbox("Theme", ["light", "dark"],230index=["light", "dark"].index(231st.session_state.get("user_preferences", {}).get("theme", "light")232))233234if st.button("Save Preferences"):235st.session_state.user_preferences["theme"] = theme236save_user_preferences()237st.success("Preferences saved!")238```239240#### Multi-Tenant Applications241242```python243def get_user_tenant():244"""Get tenant information for current user."""245if not st.user.is_authenticated:246return None247248# Extract tenant from user email domain or profile249email_domain = st.user.email.split('@')[1]250tenant = get_tenant_by_domain(email_domain)251return tenant252253def load_tenant_data(tenant_id):254"""Load tenant-specific data and configuration."""255return {256"name": get_tenant_name(tenant_id),257"settings": get_tenant_settings(tenant_id),258"data": get_tenant_data(tenant_id)259}260261# Multi-tenant app logic262if st.user.is_authenticated:263tenant = get_user_tenant()264265if tenant:266# Load tenant-specific configuration267tenant_data = load_tenant_data(tenant.id)268269# Configure app for tenant270st.set_page_config(271page_title=f"{tenant_data['name']} Dashboard",272page_icon=tenant.icon273)274275st.title(f"{tenant_data['name']} Dashboard")276st.write(f"Welcome, {st.user.email}")277278# Tenant-specific functionality279display_tenant_data(tenant_data['data'])280else:281st.error("No tenant found for your account")282else:283st.error("Please log in to continue")284```285286#### Authentication Callbacks287288```python289def on_login_success():290"""Handle successful login."""291st.session_state.login_timestamp = time.time()292st.session_state.user_preferences = load_user_preferences(st.user.id)293294# Log login event295log_user_event(st.user.id, "login", {296"timestamp": st.session_state.login_timestamp,297"ip_address": st.context.headers.get("X-Forwarded-For", "unknown")298})299300def on_logout():301"""Handle user logout."""302# Save any pending changes303if "user_data" in st.session_state:304save_user_data(st.user.id, st.session_state.user_data)305306# Clear session state307for key in list(st.session_state.keys()):308if key.startswith("user_"):309del st.session_state[key]310311# Log logout event312log_user_event(st.user.id, "logout", {313"timestamp": time.time()314})315316# Authentication state management317if "auth_checked" not in st.session_state:318st.session_state.auth_checked = True319320if st.user.is_authenticated:321on_login_success()322323# Check for logout action324if st.session_state.get("logging_out", False):325on_logout()326st.logout()327del st.session_state.logging_out328st.rerun()329```