Skip to content

Streamlit-Authenticator: How to Secure User Authentication in Streamlit Apps

Updated on

Streamlit has revolutionized the way we develop and deploy apps to the cloud since its inception in 2019. However, as the need for secure user authentication in Streamlit apps has become more apparent, a solution has emerged in the form of Streamlit-Authenticator. This article will provide a comprehensive guide on how to use Streamlit-Authenticator to add secure user authentication to your Streamlit apps.

What is Streamlit-Authenticator?

Streamlit-Authenticator is a secure authentication module that allows you to validate user credentials in your Streamlit application. With features like password reset, new user registration, and forgotten password and username widgets, Streamlit-Authenticator ensures that your app is secure and accessible only to authorized users. It's important to note that while this technique adds some level of security, it is not comparable to proper authentication with an SSO provider.

Have you heard of this awesome Data Analysis & Data Visualisation tool, that turns your Streamlit App into Tableau?

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a tableau-alternative UI into your own Streamlit app effortlessly. Check out this amazing video how to explore data with pygwalker (opens in a new tab) demonstrating the detailed steps for empowering your Streamlit app with this powerful Data Visualization Python Library!


Special Thanks to Sven and his great contribution (opens in a new tab) to PyGWalker community!

Additionally, you can also check out PyGWalker GitHub Page (opens in a new tab) for more PyGWalker examples.

Installation and Setup of Streamlit-Authenticator

Streamlit-Authenticator is a powerful tool that can be easily integrated into your Streamlit application. However, before you can start using it, you need to install it and set it up. This process is straightforward and can be accomplished in a few steps.

How to Install Streamlit-Authenticator

Installing Streamlit-Authenticator is as simple as running a pip install command in your terminal. Here's how you can do it:

pip install streamlit-authenticator

This command tells pip, the Python package installer, to download and install Streamlit-Authenticator from the Python Package Index (PyPI). Once the installation is complete, you can import Streamlit-Authenticator in your Streamlit app like any other Python package.

Setting Up Streamlit-Authenticator

After installing Streamlit-Authenticator, the next step is to set it up. This involves configuring Streamlit-Authenticator to work with your specific Streamlit app. Here's a step-by-step guide on how to do it:

  1. Import Streamlit-Authenticator in your Streamlit app:
import streamlit_authenticator as sa
  1. Initialize Streamlit-Authenticator with your app's specific settings:
auth = sa.Authenticator(
    SECRET_KEY,
    token_url="/token",
    token_ttl=3600,
    password_hashing_method=sa.PasswordHashingMethod.BCRYPT,
)
  1. Use the auth.login_required decorator to protect your Streamlit routes:
@auth.login_required
def protected():
    st.write("This is a protected route.")

Implementing User Authentication in Streamlit with Streamlit-Authenticator

Now that you have installed and set up Streamlit-Authenticator, it's time to add a user authentication service to your Streamlit app. This involves creating login and registration forms, handling user sessions, and more.

Adding User Authentication Service in Streamlit

To add a user authentication service in Streamlit, you need to create a login form where users can enter their credentials. Here's an example of how you can do this using Streamlit-Authenticator:

@st.route("/login")
def login():
    username = st.text_input("Username")
    password = st.text_input("Password", type="password")
 
    if st.button("Login"):
        user = auth.authenticate(username, password)
        if user is not None:
            auth.login_user(user)
            st.success("Logged in successfully.")
        else:
            st.error("Invalid username or password.")

Implementing User Authentication Without SSO

If you cannot implement single sign-on (SSO), don't worry. Streamlit-Authenticator allows you to add basic authentication to your Streamlit app without SSO. This involves creating a global password that's shared between all users. Here's how you can do it:

## .streamlit/secrets.toml
password = "streamlit123"

Then, in your Streamlit app, you can check the entered password against the stored password:

password = st.text_input("Password", type="password")
 
if password == st.secrets["password"]:
    st.success("Access granted.")
else:
    st.error("Access denied.")

Understanding Streamlit's Secrets Management

Streamlit's secrets management feature plays a crucial role in user authentication. It allows you to securely store sensitive information, such as passwords and API keys, outside of your code. This is essential for maintaining the security of your Streamlit app and the privacy of your users.

I apologize for the confusion earlier. Let's dive deeper into each section with more details, examples, and facts.

Advanced Features of Streamlit-Authenticator

Streamlit-Authenticator is not just about basic user authentication. It comes packed with several advanced features that provide a comprehensive solution for user management in your Streamlit apps. These features include widgets for password reset, new user registration, and handling forgotten password and username scenarios. Let's explore each of these features in detail.

Creating a Password Reset Widget

One of the key features of Streamlit-Authenticator is the ability to create a password reset widget. This is an essential feature for any application that handles user authentication. Here's a step-by-step guide on how you can create a password reset widget using Streamlit-Authenticator:

  1. First, create a new route in your Streamlit app for the password reset form:
@st.route("/password-reset")
def password_reset():
    ...
  1. Inside this route, create a form where users can enter their email address:
email = st.text_input("Enter your email address")
if st.button("Reset Password"):
    ...
  1. When the user submits the form, use Streamlit-Authenticator to generate a password reset link:
reset_link = auth.generate_password_reset_link(email)
  1. Finally, send this link to the user's email address. You can use any email library in Python, such as smtplib or yagmail, to send the email.

Creating a New User Registration Widget

Streamlit-Authenticator makes it easy to add a new user registration widget to your Streamlit app. This widget allows new users to create an account by entering their desired username and password. Here's how you can create a new user registration widget using Streamlit-Authenticator:

  1. Create a new route in your Streamlit app for the registration form:
@st.route("/register")
def register():
    ...
  1. Inside this route, create a form where users can enter their desired username and password:
username = st.text_input("Choose a username")
password = st.text_input("Choose a password", type="password")
if st.button("Register"):
    ...
  1. When the user submits the form, use Streamlit-Authenticator to create a new user account with the entered credentials:
user = auth.create_user(username, password)
st.success("Account created successfully.")

Creating a Forgotten Password Widget

If a user forgets their password, a forgotten password widget can be very helpful. This widget allows users to reset their password by entering their email address. Here's how you can create a forgotten password widget using Streamlit-Authenticator:

  1. Create a new route in your Streamlit app for the forgotten password form:
@st.route("/forgot-password")
def forgot_password():
    ...
  1. Inside this route, create a form where users can enter their email address:
email = st.text_input("Enter your email address")
if st.button("Reset Password"):
    ...
  1. When the user submits the form, use Streamlit-Authenticator to generate a password reset link and send it to the user's email address.

Creating a Forgotten Username Widget

Just like the forgotten password widget, a forgotten username widget can also be useful for users who forget their usernames. This widget allows users to retrieve their username by entering their email address. Here's how you can create a forgotten username widget using Streamlit-Authenticator:

  1. Create a new route in your Streamlit app for the forgotten username form:
@st.route("/forgot-username")
def forgot_username():
    ...
  1. Inside this route, create a form where users can enter their email address:
email = st.text_input("Enter your email address")
if st.button("Retrieve Username"):
    ...
  1. When the user submits the form, use Streamlit-Authenticator to retrieve the user's username and send it to the user's email address.
username = auth.get_username(email)
st.success(f"Your username is {username}.")

These advanced features of Streamlit-Authenticator make it a comprehensive solution for user authentication in Streamlit apps. By using these features, you can ensure that your app is not only secure but also user-friendly.

Streamlit-Authenticator: Beyond Basic Authentication

While Streamlit-Authenticator provides a robust solution for user authentication, it also offers a range of additional features that can enhance the user experience and streamline user management. These features, such as user roles and permissions, multi-factor authentication, and integration with third-party authentication providers, can add an extra layer of security and flexibility to your Streamlit apps.

  • User Roles and Permissions: Streamlit-Authenticator supports user roles and permissions, allowing you to control what each user can and cannot do in your app. For example, you can create roles for administrators, editors, and viewers, each with different permissions. This can be particularly useful for apps that have different types of users with different needs and responsibilities.

  • Multi-Factor Authentication: For added security, Streamlit-Authenticator supports multi-factor authentication (MFA). With MFA, users are required to provide two or more pieces of evidence (or factors) to authenticate themselves. These factors can include something they know (like a password), something they have (like a physical token or a smartphone), or something they are (like a fingerprint or other biometric data).

  • Integration with Third-Party Authentication Providers: Streamlit-Authenticator can also be integrated with third-party authentication providers, such as Google, Facebook, and Twitter. This allows users to log in to your app using their existing accounts on these platforms, making the login process faster and more convenient.

Conclusion

Streamlit-Authenticator provides a comprehensive solution for user authentication in Streamlit apps. From basic authentication features like login and registration to advanced features like password reset, user roles and permissions, multi-factor authentication, and integration with third-party providers, Streamlit-Authenticator has everything you need to secure your app and provide a smooth user experience.

However, it's worth noting that while Streamlit-Authenticator is a powerful tool, it's not without its disadvantages. For instance, it may not be suitable for apps that require a high level of security, such as banking or healthcare apps. Also, while it's relatively easy to set up, it does require some knowledge of Python and web development.

Despite these potential drawbacks, Streamlit-Authenticator remains a popular choice for user authentication in Streamlit apps due to its ease of use, flexibility, and robust set of features.

Have you heard of this awesome Data Analysis & Data Visualisation tool, that turns your Streamlit App into Tableau?

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a tableau-alternative UI into your own Streamlit app effortlessly.

PyGWalker for Data visualization in Streamlit (opens in a new tab)

Frequently Asked Questions

Q: How do I authenticate Streamlit?

A: You can authenticate Streamlit using Streamlit-Authenticator, a secure authentication module that allows you to validate user credentials in your Streamlit application. It provides features like password reset, new user registration, and forgotten password and username widgets.

Q: How do I add user authentication to Streamlit?

A: You can add user authentication to Streamlit by installing and setting up Streamlit-Authenticator. Once set up, you can use it to create login and registration forms, handle user sessions, and more.

Q: What is Streamlit authenticator?

A: Streamlit-Authenticator is a secure authentication module for Streamlit apps. It allows you to validate user credentials, manage user sessions, and provide features like password reset, new user registration, and forgotten password and username widgets.

Q: What are the disadvantages of Streamlit?

A: While Streamlit is a powerful tool for creating data apps, it does have some disadvantages. For instance, it may not be suitable for apps that require a high level of security, such as banking or healthcare apps. Also, while it's relatively easy to set up, it does require some knowledge of Python and web development.