准备工作
pip install streamlit-authenticator
创建 YAML 文件:config.yaml
credentials:
usernames:
liba001:
email: jsmith@gmail.com
name: John Smith
password: abc # To be replaced with hashed password
liba002:
email: rbriggs@gmail.com
name: Rebecca Briggs
password: def # To be replaced with hashed password
cookie:
expiry_days: 365
key: random_signature_key # Must be string
name: random_cookie_name
preauthorized:
emails:
- melsby@gmail.com
使用 Hasher 模块将纯文本密码转换为哈希密码:
import streamlit_authenticator as stauth
hashed_passwords = stauth.Hasher(['abc', 'def']).generate()
print(hashed_passwords)
将 YAML 文件中的纯文本密码替换为生成的哈希密码
开始主程序
import yaml
from yaml.loader import SafeLoader
with open('config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)
authenticator = Authenticate(
config['credentials'],
config['cookie']['name'],
config['cookie']['key'],
config['cookie']['expiry_days'],
config['preauthorized']
)
name, authentication_status, username = authenticator.login('Login', 'main')
if authentication_status:
authenticator.logout('Logout', 'main')
st.write(f'Welcome *{name}*')
st.title('Some content')
elif authentication_status == False:
st.error('Username/password is incorrect')
elif authentication_status == None:
st.warning('Please enter your username and password')