ログイン機能

次のようにauth_utils.pyを作成する。

import streamlit as st
import streamlit_authenticator as stauth

import yaml
from yaml.loader import SafeLoader

with open('config.yaml') as file:
config = yaml.load(file, Loader=SafeLoader)

authenticator = stauth.Authenticate(
config['credentials'],
config['cookie']['name'],
config['cookie']['key'],
config['cookie']['expiry_days']
)

def login_required(contents):
def wrapper(*args, **kwargs):
try:
authenticator.login()
except Exception as e:
st.error(e)

if st.session_state['authentication_status']:
st.toast('ログインに成功しました。')
authenticator.logout()
contents(*args, **kwargs)
elif st.session_state['authentication_status'] is False:
st.error('ユーザー名かパスワードが正しくありません。')
elif st.session_state['authentication_status'] is None:
st.warning('ユーザー名とパスワードを入力してください。')
return wrapper

呼び出し

コンテンツページにログインを課すのは次の要領。

import auth_utils
from auth_utils import login_required

@login_required
def main():
pass

認証情報

クッキーとアカウントのサンプルとして、開発ページにあるconfig.yamlをあげる。

cookie:
expiry_days: 30
key: some_signature_key # Must be a string
name: some_cookie_name
credentials:
usernames:
jsmith:
email: jsmith@gmail.com
failed_login_attempts: 0 # Will be managed automatically
first_name: John
last_name: Smith
logged_in: False # Will be managed automatically
password: abc # Will be hashed automatically
roles: # Optional
- admin
- editor
- viewer
rbriggs:
email: rbriggs@gmail.com
failed_login_attempts: 0 # Will be managed automatically
first_name: Rebecca
last_name: Briggs
logged_in: False # Will be managed automatically
password: def # Will be hashed automatically
roles: # Optional
- viewer
oauth2: # Optional
google: # Follow instructions: https://developers.google.com/identity/protocols/oauth2
client_id: # To be filled
client_secret: # To be filled
redirect_uri: # URL to redirect to after OAuth2 authentication
microsoft: # Follow instructions: https://learn.microsoft.com/en-us/graph/auth-register-app-v2
client_id: # To be filled
client_secret: # To be filled
redirect_uri: # URL to redirect to after OAuth2 authentication
tenant_id: # To be filled
pre-authorized: # Optional
emails:
- melsby@gmail.com