【Streamlit入門】ログイン機能の作り方

Python

Streamlitで、Streamlit-Authenticatorというライブラリを用いてログイン機能を作る方法を紹介します。

Streamlit-Authenticatorのインストール

今回、Streamlitでログイン機能を作成するためにStreamlit-Authenticatorというライブラリを利用します。

GitHub - mkhorasani/Streamlit-Authenticator: A secure authentication module to manage user access in a Streamlit application.
A secure authentication module to manage user access in a Streamlit application. - mkhorasani/Streamlit-Authenticator

下記のコマンドでインストールできます。

pip install streamlit-authenticator

設定ファイルの準備

streamlit-authenticatorではログインできるユーザーを事前に設定ファイルに設定しておく必要があります。

credentials:
  usernames:
    testuser:
      email: test@example.com
      name: testuser
      password: $2b$12$xxxxxxxxxxxxxxxxxxxxxxxxxxx # 左の値はダミーです。パスワードのハッシュ値をここに入力します。
cookie:
  expiry_days: 30
  key: some_signature_key
  name: some_cookie_name

上記の設定ファイルを解説します。

credentialsにはusernamesの下にユーザー名を列挙することで、ログイン可能なユーザーの設定を行えます。
そしてpasswordにはパスワードのハッシュ値を設定します。たとえばパスワードをabcとするとabcのハッシュ値を設定します。

ではハッシュ値はどのように算出すればよいのでしょうか。
それは以下の方法によってコマンドラインもしくはWindows PowerShellから算出可能です。

>>> import streamlit_authenticator as stauth
>>> stauth.Hasher(['abc']).generate()
['$2b$12$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx']

# xxxxxの部分はダミーです。

この値を先ほどの設定ファイルのpasswordの部分に設定します。

main.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']
)

次にログイン画面を出力します。

authenticator.login('ログイン', 'main')

第一引数にはログインフォームの名前を指定します。
第二引数にはログインフォームの場所を指定します。mainsidebarを指定できます。

最後にログイン後の処理を記入します。

if st.session_state["authentication_status"]:
    authenticator.logout('ログアウト', 'main')
    st.write(f'ようこそ *{st.session_state["name"]}* さん!')
    st.title('ログインに成功しました。')
elif st.session_state["authentication_status"] is False:
    st.error('ユーザー名/パスワードが不正です')
elif st.session_state["authentication_status"] is None:
    st.warning('ユーザー名とパスワードを入力してください')

まず、最初のif文if st.session_state["authentication_status"]:でログイン済みかどうかを判断します。
ログイン済みの場合は、下記のブロックが実行されます。

    authenticator.logout('ログアウト', 'main')
    st.write(f'ようこそ *{st.session_state["name"]}* さん!')
    st.title('ログインに成功しました。')

authenticator.logout('ログアウト', 'main', key='unique_key')はログアウトボタンを作成します。
第一引数にはログアウトボタンの名前、
第二引数にはログアウトボタンの場所を指定します。mainsidebarを指定できます。

もし、ログイン済みでない場合は次のif文elif st.session_state["authentication_status"] is False:でログイン失敗であるかどうかを判断します。ユーザー名やパスワードを間違えた場合にはログイン失敗と判断され、st.error('ユーザー名/パスワードが不正です')により、エラーメッセージが出力されます。

ログイン成功でもログイン失敗でもない場合、elif st.session_state["authentication_status"] is None:が評価されます。ログインページに最初に訪れた際にはこちらの条件がTrueになり、st.warning('ユーザー名とパスワードを入力してください')で案内が表示されます。

以下、コードの全体を記載しておきます。

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']
)

authenticator.login('ログイン', 'main')

if st.session_state["authentication_status"]:
    authenticator.logout('ログアウト', 'main')
    st.write(f'ようこそ *{st.session_state["name"]}* さん!')
    st.title('ログインに成功しました。')
elif st.session_state["authentication_status"] is False:
    st.error('ユーザー名/パスワードが不正です')
elif st.session_state["authentication_status"] is None:
    st.warning('ユーザー名とパスワードを入力してください')

解説は以上です!コピペすれば結構簡単に作れるので、ぜひ試してみてください!

楽天Kobo電子書籍ストア
¥2,420 (2025/03/20 01:49時点 | 楽天市場調べ)
\楽天ポイント4倍セール!/
楽天市場

タイトルとURLをコピーしました