4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamlitに認証機能が追加された!

Posted at

はじめに

Streamlitのバージョン1.42.0からOpenID Connect(OIDC)によるユーザー認証が追加されました。

さっそく試してみました。

OIDCプロバイダーの準備

Google IdentityやMicrosoft Entra IDが有名ですが、今回はAuth0で試してみます。

ローカルで開発しているので、OIDCプロバイダーのAllowed Callback URLsにhttp://localhost:8501/oauth2callbackを追加しておきます。

実装

OIDCプロバイダーの設定

.streamlit/secrets.tomlに使用するIDプロバイダーの設定を記載します。
今回はAuth0の例です。

[auth]
redirect_uri = "http://localhost:8501/oauth2callback"
cookie_secret = "xxx"

[auth.auth0]
client_id = "xxx"
client_secret = "xxx"
server_metadata_url = (
    "https://{account}.{region}.auth0.com/.well-known/openid-configuration"
)
client_kwargs = { "prompt" = "login" }

redirect_uriclient_idなどを設定します。
複数プロバイダーを設定することも可能です。

Streamlitのコード

main.py
import streamlit as st

if not st.experimental_user.is_logged_in:
    if st.button("Login with Auth0"):
        st.login("auth0")
else:
    st.write(f"Hello, {st.experimental_user.name}!")
    st.button("Log out", on_click=st.logout)
  • st.login()
    • ユーザーをIDプロバイダーにリダイレクト
  • st.experimental_user
    • is_logged_in属性でログイン状態を確認できる
  • st.logout()
    • ユーザーのブラウザからIDクッキーを削除

テスト

main.pyを実行して、ブラウザにアクセスすると設定したログインボタンが表示されます。

image.png

このボタンをクリックすると、Auth0のログイン画面が表示されます。

image.png

Auth0でユーザー管理しているユーザーでログインすると、成功して画面が遷移します。

image.png

当たり前ですが、ユーザー管理していないアカウントでログインしようとすると失敗し後続の処理に行けません。

image.png

ちゃんとユーザー認証が機能していることが確認できました!

おわりに

Streamlitに追加された認証機能を試してみました。
標準機能として認証が追加されたので、開発しやすくなったのではないでしょうか。
ユーザー認証機能によって、ユーザーに合わせてアプリをパーソナライズすることで可能になります。
セッション間の履歴が保存されるチャットボットなど、様々なユースケースで利用できそうです!

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?