A faster way to build and share data apps
User authentication, login/logout functionality, and user information access. Streamlit provides built-in authentication capabilities for securing applications and managing user sessions.
Access current user information and profile data.
user: UserInfoProxyThe user object provides access to authenticated user information including profile data, authentication status, and user attributes.
Example usage:
# Check if user is authenticated
if st.user.is_authenticated:
st.write(f"Welcome, {st.user.email}!")
st.write(f"User ID: {st.user.id}")
# Access user profile
if hasattr(st.user, 'name'):
st.write(f"Name: {st.user.name}")
# Check user permissions
if st.user.has_permission('admin'):
st.write("Admin access granted")
else:
st.write("Please log in to continue")Functions for managing user authentication flow.
def login(provider, *, oauth2=None):
"""
Initiate user login process with specified authentication provider.
Args:
provider (str): Authentication provider name
oauth2 (dict, optional): OAuth2 configuration parameters
Returns:
bool: True if login was successful
"""
def logout():
"""
Log out the current user and clear authentication state.
Returns:
bool: True if logout was successful
"""Example usage:
# Login with different providers
if not st.user.is_authenticated:
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Login with Google"):
st.login("google")
with col2:
if st.button("Login with GitHub"):
st.login("github")
with col3:
if st.button("Login with Microsoft"):
st.login("microsoft")
else:
# User is authenticated
st.success(f"Logged in as {st.user.email}")
if st.button("Logout"):
st.logout()
st.rerun()
# Custom OAuth2 configuration
if st.button("Login with Custom Provider"):
oauth_config = {
"client_id": st.secrets["oauth_client_id"],
"client_secret": st.secrets["oauth_client_secret"],
"redirect_uri": "https://myapp.streamlit.app/auth/callback"
}
st.login("custom", oauth2=oauth_config)Deprecated user information interface maintained for backward compatibility.
experimental_user: DeprecatedUserInfoProxyExample usage:
# Deprecated - use st.user instead
if st.experimental_user.email:
st.write(f"User: {st.experimental_user.email}")def show_login_page():
"""Display login page with provider options."""
st.title("Welcome")
st.write("Please log in to access the application")
# Provider selection
provider = st.selectbox(
"Choose login method:",
["google", "github", "microsoft", "azure"]
)
if st.button(f"Login with {provider.title()}"):
success = st.login(provider)
if success:
st.success("Login successful!")
st.rerun()
else:
st.error("Login failed. Please try again.")
def show_authenticated_app():
"""Display main application for authenticated users."""
# Header with user info and logout
col1, col2 = st.columns([3, 1])
with col1:
st.title("My Dashboard")
with col2:
st.write(f"👤 {st.user.email}")
if st.button("Logout"):
st.logout()
st.rerun()
# Main application content
st.write("Welcome to your dashboard!")
# ... rest of app
# Main app logic
if st.user.is_authenticated:
show_authenticated_app()
else:
show_login_page()def check_user_role():
"""Check user role and permissions."""
if not st.user.is_authenticated:
return None
# Get user role from profile or database
user_role = getattr(st.user, 'role', 'user')
return user_role
def require_role(required_role):
"""Decorator to require specific user role."""
def decorator(func):
def wrapper(*args, **kwargs):
current_role = check_user_role()
if current_role != required_role:
st.error(f"Access denied. {required_role.title()} role required.")
st.stop()
return func(*args, **kwargs)
return wrapper
return decorator
@require_role('admin')
def show_admin_panel():
"""Admin-only functionality."""
st.title("Admin Panel")
st.write("Admin controls here")
# Usage
user_role = check_user_role()
if user_role == 'admin':
show_admin_panel()
elif user_role == 'user':
st.title("User Dashboard")
st.write("User content here")
else:
st.error("Please log in to continue")
st.stop()def initialize_user_session():
"""Initialize user session state."""
if "user_initialized" not in st.session_state:
st.session_state.user_initialized = True
if st.user.is_authenticated:
# Load user preferences
st.session_state.user_preferences = load_user_preferences(st.user.id)
st.session_state.user_data = load_user_data(st.user.id)
def save_user_preferences():
"""Save current user preferences."""
if st.user.is_authenticated:
save_preferences_to_db(st.user.id, st.session_state.user_preferences)
# Initialize on app start
initialize_user_session()
# User-specific functionality
if st.user.is_authenticated:
# Display personalized content
st.title(f"Welcome back, {getattr(st.user, 'name', st.user.email)}!")
# User preferences
with st.expander("Preferences"):
theme = st.selectbox("Theme", ["light", "dark"],
index=["light", "dark"].index(
st.session_state.get("user_preferences", {}).get("theme", "light")
))
if st.button("Save Preferences"):
st.session_state.user_preferences["theme"] = theme
save_user_preferences()
st.success("Preferences saved!")def get_user_tenant():
"""Get tenant information for current user."""
if not st.user.is_authenticated:
return None
# Extract tenant from user email domain or profile
email_domain = st.user.email.split('@')[1]
tenant = get_tenant_by_domain(email_domain)
return tenant
def load_tenant_data(tenant_id):
"""Load tenant-specific data and configuration."""
return {
"name": get_tenant_name(tenant_id),
"settings": get_tenant_settings(tenant_id),
"data": get_tenant_data(tenant_id)
}
# Multi-tenant app logic
if st.user.is_authenticated:
tenant = get_user_tenant()
if tenant:
# Load tenant-specific configuration
tenant_data = load_tenant_data(tenant.id)
# Configure app for tenant
st.set_page_config(
page_title=f"{tenant_data['name']} Dashboard",
page_icon=tenant.icon
)
st.title(f"{tenant_data['name']} Dashboard")
st.write(f"Welcome, {st.user.email}")
# Tenant-specific functionality
display_tenant_data(tenant_data['data'])
else:
st.error("No tenant found for your account")
else:
st.error("Please log in to continue")def on_login_success():
"""Handle successful login."""
st.session_state.login_timestamp = time.time()
st.session_state.user_preferences = load_user_preferences(st.user.id)
# Log login event
log_user_event(st.user.id, "login", {
"timestamp": st.session_state.login_timestamp,
"ip_address": st.context.headers.get("X-Forwarded-For", "unknown")
})
def on_logout():
"""Handle user logout."""
# Save any pending changes
if "user_data" in st.session_state:
save_user_data(st.user.id, st.session_state.user_data)
# Clear session state
for key in list(st.session_state.keys()):
if key.startswith("user_"):
del st.session_state[key]
# Log logout event
log_user_event(st.user.id, "logout", {
"timestamp": time.time()
})
# Authentication state management
if "auth_checked" not in st.session_state:
st.session_state.auth_checked = True
if st.user.is_authenticated:
on_login_success()
# Check for logout action
if st.session_state.get("logging_out", False):
on_logout()
st.logout()
del st.session_state.logging_out
st.rerun()Install with Tessl CLI
npx tessl i tessl/pypi-streamlit