Streamlit Authenticator登录后认证状态始终为None问题求助
问题排查与解决方案
1. 修正authenticator.login()的调用方式
你代码里的authenticator.login('main')参数传递有误,login方法的第一个参数是表单标题,位置参数需要用关键字location指定。正确的做法是直接解构返回的三个值,不需要额外判断输出是否为空:
# Authenticate user authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], ) # 直接解构login返回的三个值 name, authentication_status, username = authenticator.login(location='main') if authentication_status == False: st.error("用户名/密码不正确,请重试。") if authentication_status == None: st.warning("请登录后使用应用。") if authentication_status: st.success(f"欢迎 {name}!您已登录。")
2. 验证credentials.yaml的结构
确保你的配置文件完全符合streamlit-authenticator的要求,结构必须如下(注意哈希密码要和users.pkl里的对应):
credentials: usernames: chris: name: Christopher Ode email: chris@example.com password: <从users.pkl中取出的哈希值> john: name: John Doe email: john@example.com password: <从users.pkl中取出的哈希值> cookie: name: healthcare_translation_auth key: 随机生成的长密钥字符串 expiry_days: 30
如果credentials下缺少usernames层级,或者用户名、密码不匹配,会导致认证状态始终异常。
3. 确保哈希密码生成与存储一致
确认你生成哈希密码的代码是正确的,比如:
import pickle from pathlib import Path import streamlit_authenticator as stauth # 原始密码列表 passwords = ["chris的密码", "john的密码"] hashed_passwords = stauth.Hasher(passwords).generate() # 写入pkl文件 file_path = Path(__file__).parent / "users.pkl" with file_path.open("wb") as file: pickle.dump(hashed_passwords, file)
生成后要把每个哈希值准确填入credentials.yaml对应用户的password字段,两者必须完全一致。
4. 调整组件顺序避免状态丢失
把认证逻辑放在页面最顶部,在任何其他组件(比如st.title)之前执行,防止页面刷新时认证状态被重置:
# 先执行认证逻辑 with open('credentials.yaml') as file: config = yaml.load(file, Loader=SafeLoader) file_path = Path(__file__).parent / "users.pkl" with file_path.open("rb") as file: hashed_passwords = pickle.load(file) authenticator = stauth.Authenticate( config['credentials'], config['cookie']['name'], config['cookie']['key'], config['cookie']['expiry_days'], ) name, authentication_status, username = authenticator.login(location='main') # 认证状态判断 if authentication_status == False: st.error("用户名/密码不正确,请重试。") if authentication_status == None: st.warning("请登录后使用应用。") if authentication_status: # 登录成功后再显示应用内容 st.title('Healthcare Translation App') st.success(f"欢迎 {name}!您已登录。") # 后续应用逻辑...
5. 检查Streamlit版本与Session State
确保你的Streamlit版本在1.10.0以上,且没有其他代码意外修改了st.session_state中的认证相关键值(比如authentication_status、name)。
内容的提问来源于stack exchange,提问作者ode christopher
相关产品推荐
相关产品推荐

