業界・業務から探す
導入目的・課題から探す
データ・AIについて学ぶ
News
Hakkyについて
ウェビナーコラム
◆トップ【AI・機械学習】
AI

執筆者:Handbook編集部

StreamlitでBasic認証を行う方法

概要

本記事では Streamlit で Basic 認証を実現する方法について紹介します。

ファイル構成

本記事では、次のようなファイル構成を前提として進めていきます。

src/
  ├ app.py
  └ config.yml

コード

以下のようにして、Streamlit 上で Basic 認証を実装することができます。

src/app.py

import streamlit as st
import streamlit_authenticator as stauth

import yaml
from yaml.loader import SafeLoader

def run():
    st.title("Basic Authentication")

    # ユーザーの資格情報取得
    config = []
    with open('src/config.yml') as file:
        config = yaml.load(file, Loader = SafeLoader)

    # 認証
    authenticator = stauth.Authenticate(
        config['credentials'],
        config['cookie']['name'],
        config['cookie']['key'],
        config['cookie']['expiry_days'],
    )
    name, authentication_status, user_name = authenticator.login("Login", "main")

    # 判定
    if authentication_status:
        """
        認証成功時の処理
        """
    elif authentication_status is False:
        st.error("Username/password is incorrect")
    elif authentication_status is None:
        st.warning("Please enter your username and password")

if __name__ == "__main__":
    run()

src/config.yml

credentials:
  usernames:
    hakky:
      email: hakky@example.com
      name: hakky
      password: $2b$12$7JTIe3YFtG6IebKUQ6wpbOX9r4IRE9JynqIDgy658LWm6x69ecHgm
cookie:
  expiry_days: 90
  key: some_key
  name: some_cookie_name

パスワードの Hash 化

src/config.ymlにある Hash 化されたパスワードは、以下の方法で取得できます。

import streamlit_authenticator as stauth

password = "PasswordsAreHashedAndThereforeSafe"

hashed_password = stauth.Hasher([password]).generate()

print(hashed_password)

# ['$2b$12$7JTIe3YFtG6IebKUQ6wpbOX9r4IRE9JynqIDgy658LWm6x69ecHgm']

参照

info
備考

Hakky ではエンジニアを募集中です!まずは話してみたいなどでも構いませんので、ぜひお気軽に採用ページからお問い合わせくださいませ。

2025年06月13日に最終更新
読み込み中...