• Stars
    star
    1,527
  • Rank 30,669 (Top 0.7 %)
  • Language
    Python
  • License
    Other
  • Created about 3 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A secure authentication module to manage user access in a Streamlit application.

Streamlit-Authenticator Downloads

A secure authentication module to validate user credentials in a Streamlit application.

To learn more please refer to my book Web Application Development with Streamlit.

Installation

Streamlit-Authenticator is distributed via PyPI:

pip install streamlit-authenticator

Example

Using Streamlit-Authenticator is as simple as importing the module and calling it to verify your predefined users' credentials.

import streamlit as st
import streamlit_authenticator as stauth

1. Hashing passwords

  • Initially create a YAML configuration file and define your users' credentials (names, usernames, and placeholders for the hashed passwords). In addition, enter a name, random key, and number of days to expiry for a JWT cookie that will be stored on the client's browser to enable passwordless reauthentication. If you do not require reauthentication, you may set the number of days to expiry to 0. Finally, define a list of preauthorized emails of users who can register and add their credentials to the configuration file with the use of the register_user widget.
credentials:
  usernames:
    jsmith:
      email: jsmith@gmail.com
      name: John Smith
      password: # Placeholder for hashed password for 'abc'
    rbriggs:
      email: rbriggs@gmail.com
      name: Rebecca Briggs
      password: # Placeholder for hashed password for 'def'
cookie:
  expiry_days: 30
  key: some_signature_key # Must be string
  name: some_cookie_name
preauthorized:
  emails:
  - melsby@gmail.com
  • Then use the Hasher module to convert the plain text passwords into hashed passwords.
hashed_passwords = stauth.Hasher(['abc', 'def']).generate()
  • Finally replace the plain text passwords in the configuration file with the hashed passwords.

2. Creating a login widget

  • Subsequently import the configuration file into your script and create an authentication object.
import yaml
from yaml.loader import SafeLoader

with open('../config.yaml') as file:
    config = yaml.load(file, Loader=SafeLoader)

authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['preauthorized']
)
  • Then finally render the login module as follows. Here you will need to provide a name for the login form, and specify where the form should be located i.e. main body or sidebar (will default to main body).
name, authentication_status, username = authenticator.login('Login', 'main')

3. Authenticating users

  • You can then use the returned name and authentication status to allow your verified user to proceed to any restricted content. In addition, you have the ability to add an optional logout button at any location on your main body or sidebar (will default to main body). The optional key parameter for the logout widget should be used with multipage applications to prevent Streamlit from throwing duplicate key errors.
if authentication_status:
    authenticator.logout('Logout', 'main', key='unique_key')
    st.write(f'Welcome *{name}*')
    st.title('Some content')
elif authentication_status is False:
    st.error('Username/password is incorrect')
elif authentication_status is None:
    st.warning('Please enter your username and password')
  • Should you require access to the persistent name, authentication status, and username variables, you may retrieve them through Streamlit's session state using st.session_state["name"], st.session_state["authentication_status"], and st.session_state["username"]. This way you can use Streamlit-Authenticator to authenticate users across multiple pages.
if st.session_state["authentication_status"]:
    authenticator.logout('Logout', 'main', key='unique_key')
    st.write(f'Welcome *{st.session_state["name"]}*')
    st.title('Some content')
elif st.session_state["authentication_status"] is False:
    st.error('Username/password is incorrect')
elif st.session_state["authentication_status"] is None:
    st.warning('Please enter your username and password')

  • Or prompt an unverified user to enter a correct username and password.

  • Please note that logging out will revert the authentication status to None and will delete the associated reauthentication cookie as well.

4. Creating a password reset widget

  • You may use the reset_password widget to allow a logged in user to modify their password as shown below.
if authentication_status:
    try:
        if authenticator.reset_password(username, 'Reset password'):
            st.success('Password modified successfully')
    except Exception as e:
        st.error(e)

Please remember to update the config file (as shown in step 9) after you use this widget.

5. Creating a new user registration widget

  • You may use the register_user widget to allow a user to sign up to your application as shown below. If you require the user to be preauthorized, set the preauthorization argument to True and add their email to the preauthorized list in the configuration file. Once they have registered, their email will be automatically removed from the preauthorized list in the configuration file. Alternatively, to allow anyone to sign up, set the preauthorization argument to False.
try:
    if authenticator.register_user('Register user', preauthorization=False):
        st.success('User registered successfully')
except Exception as e:
    st.error(e)

Please remember to update the config file (as shown in step 9) after you use this widget.

6. Creating a forgot password widget

  • You may use the forgot_password widget to allow a user to generate a new random password. This password will be automatically hashed and saved in the configuration file. The widget will return the username, email, and new random password of the user which should then be transferred to them securely.
try:
    username_of_forgotten_password, email_of_forgotten_password, new_random_password = authenticator.forgot_password('Forgot password')
    if username_of_forgotten_password:
        st.success('New password to be sent securely')
        # Random password should be transferred to user securely
    else:
        st.error('Username not found')
except Exception as e:
    st.error(e)

Please remember to update the config file (as shown in step 9) after you use this widget.

7. Creating a forgot username widget

  • You may use the forgot_username widget to allow a user to retrieve their forgotten username. The widget will return the username and email of the user which should then be transferred to them securely.
try:
    username_of_forgotten_username, email_of_forgotten_username = authenticator.forgot_username('Forgot username')
    if username_of_forgotten_username:
        st.success('Username to be sent securely')
        # Username should be transferred to user securely
    else:
        st.error('Email not found')
except Exception as e:
    st.error(e)

8. Creating an update user details widget

  • You may use the update_user_details widget to allow a logged in user to update their name and/or email. The widget will automatically save the updated details in both the configuration file and reauthentication cookie.
if authentication_status:
    try:
        if authenticator.update_user_details(username, 'Update user details'):
            st.success('Entries updated successfully')
    except Exception as e:
        st.error(e)

Please remember to update the config file (as shown in step 9) after you use this widget.

9. Updating the configuration file

  • Please ensure that the configuration file is resaved anytime the credentials are updated or whenever the reset_password, register_user, forgot_password, or update_user_details widgets are used.
with open('../config.yaml', 'w') as file:
    yaml.dump(config, file, default_flow_style=False)

Credits

More Repositories

1

excel_word_automation

Integrate Excel with Word to generate automated reports seamlessly
33
star
2

automated_report

Generating automated word documents with Python
Python
21
star
3

colab_automation

Automating Google Colab with JavaScript to run prescheduled and dynamic Python scripts
JavaScript
19
star
4

arduino_python_radar

How to build an inexpensive mini radar system with a live dashboard
Python
17
star
5

timeseries_heatmap

Using Plotly to create a heatmap visualization of monthly and hourly data
Python
13
star
6

arduino_python_scada_system

How to build a real-time SCADA system using Python and Arduino
Python
7
star
7

online_machine_learning_app

DummyLearn.com - a free online machine learning platform. All plug & play without any coding, orchestration, or overhead.
Python
7
star
8

data_warehouse

Building a data warehouse in Python using PostgreSQL
Python
6
star
9

interactive_datetime_filter

Creating an interactive datetime filter using Pandas and Streamlit
Python
6
star
10

python_automated_email

Create an automated email pipeline with dazzling dashboards
6
star
11

dynamic_time_warping_synchronzation

Using dynamic time warping to synchronize time series data
Python
5
star
12

streamlit_dynamic_dashboard

Developing a dynamically updated dashboard with Streamlit.
Python
5
star
13

streamlit_state

A stateful implementation of Streamlit using PostgreSQL
Python
5
star
14

Trading_Sentiment_Analyzer

Trading Sentiment Analyzer will compute a normalized 'sentiment' score for any stock, currency, commodity or index by analyzing relevant and current news articles on the internet.
Python
5
star
15

maxon_python_windows_64

How to control Maxon motors using the ctypes library on Windows OS
Python
5
star
16

JobMatch

A job recommender app, using natural language processing and fuzzy matching to match job seekers with employers.
Python
4
star
17

Image_Processing_Based_Speeding_Radar

The scope of this tool, is to implement an image processing-based traffic radar that detects vehicle number plates and subsequently measures the instantaneous vehicle speed.
Jupyter Notebook
3
star
18

streamlit_ui

Develop and deploy a UI with Python in under 15 minutes
Python
2
star
19

Bank_Scan

A Fintech application using natural language processing and data mining techniques to analyze and determine the financial health of banking clients.
Python
1
star
20

Online_Association_Minining

This app harnesses the power of data mining to discover patterns in transaction data. You can use this app to apply these methods to your own data by uploading a data file and tweaking the settings on the right.
Python
1
star
21

mkhorasani

1
star
22

Streamlit-Authenticator-demo

Python
1
star