This repository demonstrates how to implement persistent session management in Streamlit using cookies. It provides a simple example of a login system that maintains user sessions across page refreshes and browser restarts.
- User authentication with test credentials
- "Remember me" functionality using cookies
- Session persistence across page refreshes
- Secure token generation
- Debug information display
- Mobile-friendly
-
Clone this repository:
-
Install the required packages:
pip install -r requirements.txt
- Run the Streamlit app:
streamlit run main.py
-
Open your browser and navigate to the provided URL (typically
http://localhost:8501
) -
Use one of the test credentials to log in:
- Username:
admin
, Password:password123
- Username:
test_user
, Password:test123
- Check the "Remember me" box to maintain your session
The app uses extra-streamlit-components
to manage cookies for session persistence. Here's a breakdown of the key components:
- Cookie Management: Uses
stx.CookieManager()
to handle cookie operations - Token Generation: Creates secure tokens using username and timestamp
- Session State: Utilizes Streamlit's session state for temporary storage
- Cookie Persistence: Implements delays to ensure proper cookie setting
Key code snippets:
# Initialize cookie manager
cookie_manager = stx.CookieManager()
# Set cookies with expiry
cookie_manager.set(
'auth_token',
token,
expires_at=expiry,
key='set_token'
)
# Get cookies
cookies = cookie_manager.get_all(key='get_cookies')
- This is a demonstration and should not be used in production without proper security measures
- The token generation is simplified for demonstration purposes
- In a production environment, you should:
- Use a secure database for user management
- Implement proper password hashing
- Use more secure token generation and validation
- Add rate limiting and other security measures
- streamlit
- extra-streamlit-components
- python-dateutil
- Cookie setting requires small delays to ensure proper persistence
- Session restoration might require a page refresh in some cases
Feel free to submit issues, fork the repository, and create pull requests for any improvements.
Apache 2.0 License - feel free to use this code in your own projects.
- Inspired by the Streamlit community's discussions on session management
- Thanks to the creators of
extra-streamlit-components
for the cookie management functionality
Fergus McKenzie-Wilson
If you found this helpful, please star the repository!