Location>code7788 >text

『Play Streamlit』--Login authentication mechanism

Popularity:49 ℃/2024-11-06 02:40:49

If yourStreamlit AppThe data used in the data is more sensitive, so it is important to protect thisAppand the data behind it from unauthorized access becomes critical.

Whether it's for the protection of trade secrets, the maintenance of user privacy, or to meet increasingly stringent compliance requirements, ensuring that only authenticated users have access to specific data and functionality has become a fundamental requirement for most applications.

login authentication, as the basis for access control, is to protectStreamlit AppThe first line of defense for security.

By implementing login authentication mechanisms, we can ensure that only legitimate users can access sensitive data, perform critical operations or view specific pages.

This paper will look at how theStreamlitAdd login authentication to multi-page applications.

From why you need login authentication, to how to implement this functionality, and finally building an example to demonstrate how you can use it in your ownStreamlit AppAdd the login authentication function to the

1. Why login authentication is needed

under constructionStreamlitAdding login authentication is not a redundant step when it comes to multi-page applications, but an important part of ensuring that the application is secure, efficient and user-friendly.

Generally speaking, we will need the login authentication function when some of the following scenarios.

1.1 Data security requirements exist

If ourStreamlit AppThe data processed contains sensitive or confidential information, such as customer data, financial data or research data.

Then, unauthorized access may lead to data leakage and unnecessary trouble.

In this case, login authentication can at least ensure that only authenticated users can access the data, which can effectively reduce the risk of data leakage.

In addition, many industries (e.g., financial, healthcare, education) have strict data protection regulations that require encrypted storage and access control for personal information and sensitive data. Login authentication is a key component in achieving these compliance requirements.

1.2 User management requirements exist

If your application has users with different roles (e.g. split between administrator, editor, viewer, etc.), each role has different permissions.

Then, the first thing you need to do is implement login authentication in order to further yourStreamlit Appcap (a poem)RBAC(Role Based Access Control)System interfacing for role-based access control.

1.3 Enhancing the user experience

When the user sees theStreamlit AppWhen security measures such as login authentication are taken, they trust the app more and are more willing to share personal information or use sensitive features.

In addition, login authentication allowsStreamlit AppIdentify and remember users to deliver personalized experiences.

For example, it is possible to set the interface theme according to the user's preferences, save the user's work progress, and so on.

2. How to achieve login authentication

Implementing a login authentication function consists of the following 4 main parts:

  1. Authentication Methods: It is common to have username + password; email or cell phone acceptance of CAPTCHA; third-party based authentication (OAuth/OpenIDetc.
  2. User information database: A relational database is generally used to store user information, which generally contains fields such as user ID, username, password hash, roles/privileges, etc.
  3. login page: Depending on the choice ofAuthentication MethodsuseStreamlitImplement a page to handle user input and login requests
  4. back-end logic: Depending on the choice ofAuthentication MethodsThe back-end implementation of the user input information is legitimate or not.

back-end logicIn addition to determining the legitimacy of user input information, sometimes, for higher security requirements, some password policies (such as requiring the length of passwords, including special characters, changing passwords on a regular basis, etc.), anti-violent cracking mechanisms (such as restricting the frequency of logging in, and locking the account for too many failed logins, etc.), as well as other means of preventing some attacks.

3. Example of login authentication

Finally, a simplified example demonstrates how theStreamlit AppAdd a login authentication mechanism.

This example mainly demonstratesStreamlitIt's how to restrict access to specific feature pages to users who are not logged in and authenticated, without the database and security parts.

First, build a multi-page application without adding the login function first.

The project directory structure is as follows:

$ tree /A /F .
Authentication
||The
\--func_pages
\---func_pages


        __init__.py

import streamlit as st

page1 = ("pages/", title="Viewing the dataset")
page2 = ("pages/", title="Plotting Line Charts")

pg = ({"Main function": [page1, page2]})
()

cap (a poem)Separate functional pages are simulated.

The running effect is as follows:

Next, add the login authentication function, for simplicity, the login username and password are fixed and written to death, and the login status is placed in thesessionCenter.

commander-in-chief (military)The modifications are as follows

# Initialize session state
if "logged_in" not in st.session_state:
    st.session_state.logged_in = False


# default user
USERNAME = "admin"
PASSWORD = "adminadmin"


# login page
def login():
    ("log in")
    ()

    username = st.text_input("user ID")
    password = st.text_input("cryptographic", type="password")

    if ("Login"):
        if username == USERNAME and password == PASSWORD:
            st.session_state.logged_in = True
            ("log in成功!")
            (0.5)
            ()
        else:
            ("user ID或cryptographic错误")


page1 = ("func_pages/", title="View Dataset")
page2 = ("func_pages/", title="Plotting line graphs")
login_page = (login, title="log in")

# The default is onlyloginweb page
pg = ([login_page])

if st.session_state.logged_in:
    pg = ({"Key Features": [page1, page2]})

()

passed statest.session_state.logged_into determine if the user is logged in.

Enter the [Main Functions] page after successful login, otherwise it stays at the [Login] page.

Add another function for logging out, based on the above code modified as follows:

def logout():
    if ("Logout"):
        st.session_state.logged_in = False
        ()

logout_page = (logout, title="Log out")

if st.session_state.logged_in:
    pg = (
        {
            "account management": [logout_page],
            "Key Features": [page1, page2],
        }
    )

The running effect is as follows:

4. Summary

This article only provides a basic login authentication implementation example, the actual application may need to be customized and extended according to specific needs.

For example, consider adding multi-factor authentication, user registration and password retrieval capabilities, and the ability to communicate with third-party identity providers such asOAuth) integration, etc.