在Streamlit官方文档中,没有提供提供安全身份验证组件。目前,第三方streamlit-authenticator提供此功能,详见引用我原来的博文,在《Streamlit应用程序使用Streamlit-Authenticator进行用户的安全身份验证实践》文中,原使用的代码报错:
authenticator = stauth.Authenticate(names, usernames, hashed_passwords,
TypeError: __init__() got multiple values for argument 'cookie_expiry_days'
报错原因是Streamlit-Authenticator包升级了,原代码发生了改变,解决办法如下:
import streamlit as st
import streamlit_authenticator as stauth
import PVForecastWeb# 此行代码被强制要求放在第一行。
st.set_page_config(layout="wide") #设置屏幕展开方式,宽屏模式布局更好credentials = {'usernames': {'xiaoyw': {'email': 'xiaoyw****@gmail.com','name': '肖永威','password': '*************'}, 'admin': {'email': 'admin***@gmail.com','name': '管理员','password': '************ '} }}authenticator = stauth.Authenticate(credentials,'some_cookie_name', 'some_signature_key', cookie_expiry_days=30)name, authentication_status, username = authenticator.login('Login', 'main')if authentication_status:with st.container():cols1,cols2 = st.columns(2)cols1.write('欢迎 *%s*' % (name))with cols2.container():authenticator.logout('Logout', 'main')PVForecastWeb.main() # 进入业务应用
elif authentication_status == False:st.error('Username/password is incorrect')
elif authentication_status == None:st.warning('Please enter your username and password')
其中,密码使用其提供的函数加密,输出字符串沾到代码中即可。
hashed_passwords = stauth.Hasher(['S0451', 'ad4516']).generate()
当然,可以使用其帮助https://github.com/mkhorasani/Streamlit-Authenticator/tree/main中的yaml配置文件,在此不再累述。
版本变化情况:
版本号 | 时间 | 说明 |
---|---|---|
v0.2.2 | May 2023 | Added a unique key for the logout button to prevent duplicate key errors. |
v0.2.1 | Jun 25, 2022 | |
v0.1.5 | May 24, 2022 | Enhanced reauthentication cookie checking,Featured ability to import credentials and cookie setting |
参考:
肖永威. Streamlit应用程序使用Streamlit-Authenticator进行用户的安全身份验证实践. CSDN博客. 2022.05