User logged out after page refresh- Need persistent session

Hello, I’m building an app that acts as a video conferencing dashboard with analytics. I am hosting the app locally and plan on eventually deploying it using docker. I am using the mutlipage functionality and tracking state for when users change pages. I am using Sqlite for my database which is storing user creds and some other settings from my app. Everything seems to be working pretty well for authentication, new users, etc. But, when a user refreshes the page from the browser they have to log back in.

I am sort of a beginner so I’ve been reading that state only keeps state while in the apps not for browser refresh. For this we would need a cookie from the browser? And from what I’ve read there were many different options throughout the last couple years some official and some unofficial so I wasn’t sure what is the best supported way of doing this today?

If anyone has a simple app that is doing at least the persistent session after login please share if you can. My goal is to first create a simple test app with a login button and message to get this working.

  • Recap: Hosted locally, eventually going in Docker
  • Using Multipage functionality with the side bar for navigation
  • Tracking state across pages
  • using authentication with sqlite as the database
  • Streamlit version 1.37.0

I think I have a solution. I’ve going to expand out to multipage and with in app state and continue to test. I was successful using the streamlit-cookies-controller to save and manage the browser cookies- New Component: Streamlit-Cookies-Controller

For anyone interested, this basic app creates a SQlite database with a single test user, then allows the user to login with those credentials. After you’re logged in you can refresh and you should see that your session state persists both for the app with a message and in the browser since you dont have to log back in.

Run this first to setup your simple database with the default user.
setup_database.py

import sqlite3
from hashlib import sha256

def create_database():
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY,
            username TEXT NOT NULL UNIQUE,
            password_hash TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

def add_user(username, password):
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    password_hash = sha256(password.encode()).hexdigest()
    try:
        c.execute('INSERT INTO users (username, password_hash) VALUES (?, ?)', (username, password_hash))
        conn.commit()
    except sqlite3.IntegrityError:
        print("Username already exists!")
    conn.close()

if __name__ == '__main__':
    create_database()
    # Add a test user
    add_user('testuser', 'password123')

Next run the app app.py

import streamlit as st
import sqlite3
from hashlib import sha256
from streamlit_cookies_controller import CookieController
import time

# Initialize the cookies controller
cookie_controller = CookieController()

# Database connection function
def get_db_connection():
    conn = sqlite3.connect('users.db')
    return conn

# Function to authenticate user
def authenticate_user(username, password):
    conn = get_db_connection()
    c = conn.cursor()
    password_hash = sha256(password.encode()).hexdigest()
    c.execute('SELECT id FROM users WHERE username = ? AND password_hash = ?', (username, password_hash))
    result = c.fetchone()
    conn.close()
    return result[0] if result else None

# Function to handle login
def login(username, password):
    user_id = authenticate_user(username, password)
    if user_id:
        # Set a cookie with the user ID
        cookie_controller.set("user_id", user_id)
        st.session_state["user_id"] = user_id
        st.success("Logged in successfully!")
        time.sleep(0.5)  # Pause briefly before rerun
        st.rerun()  # Rerun to reflect the login state immediately
    else:
        st.error("Login failed")

# Function to handle logout
def logout():
    # Clear cookie by setting it to an empty value with a past expiration
    cookie_controller.set("user_id", "", max_age=0)
    st.session_state.pop("user_id", None)
    st.success("Logged out successfully!")
    time.sleep(0.5)  # Pause briefly before rerun
    st.rerun()  # Rerun to clear the interface

# Check if user is logged in
def check_session():
    # Check if the user_id cookie exists
    user_id = cookie_controller.get("user_id")
    if user_id:
        # Restore session
        st.session_state["user_id"] = user_id
        st.success("Session restored!")

# Streamlit app layout
def main():
    st.title("Simple Streamlit Login App")
    check_session()

    if "user_id" in st.session_state:
        st.write("You are logged in.")
        if st.button("Logout"):
            logout()
    else:
        st.write("Please log in.")
        with st.form("login_form"):
            username = st.text_input("Username")
            password = st.text_input("Password", type="password")
            submitted = st.form_submit_button("Login")
            if submitted:
                login(username, password)

if __name__ == "__main__":
    main()

3 Likes