0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChainlitでBasic認証の実装

Posted at

ChainlitでBasic認証を実装したのでその記録です。2つハマってしまった点があるので、こちらでメモしてます。

動作

UIアクセス時にユーザーとパスワード入力を求められます。
image.png

ユーザIDadminでログインしたので、右上に「A」と表示され、クリックするとSettingsとLogoutが選べます。PCの再起動などしてもLoginした情報が残っているらしく、再認証を求められなかったです(ここで認証を実装できていないと勘違いして時間をかけてしまった)。もう一度、認証画面に行きたい場合はLogoutすればOKです。
image.png

環境

Pythonと追加パッケージのバージョンです。

  • Python: 3.12.2
  • Chainlit: 1.0.506
  • python-dotenv: 1.0.1

実装

事前準備

Chainlitをインストール後、ターミナルからchainlit create-secretと打ってシークレットを生成します。コードに目が行き過ぎてこのプロセスを見落としていて、少し苦しみました。
こちらの公式情報に従っています。

% chainlit create-secret
2024-05-04 18:23:58 - Loaded .env file
Copy the following secret into your .env file. Once it is set, changing it will logout all users with active sessions.
CHAINLIT_AUTH_SECRET="<secret>"

で、生成したシークレットを.envファイルに書き込みます(作っていなかったらPythonアプリケーションファイルと同じディレクトリにファイル作成)。

.env
CHAINLIT_AUTH_SECRET="<secret>"

Pythonプログラム

下記のシンプルなChainlitのプログラムに

Basic認証のここの内容を付加。

ユーザとパスワードをハードコーディングしています。ここは自由にファイルから読むでもいいかと思います。

app.py
import chainlit as cl
from dotenv import load_dotenv

load_dotenv()


@cl.on_message
async def main(message: cl.Message):
    # Send a response back to the user
    await cl.Message(
        content=f"Received: {message.content}",
    ).send()

@cl.password_auth_callback
def auth_callback(username: str, password: str):
    # Fetch the user matching username from your database
    # and compare the hashed password with the value stored in the database
    if (username, password) == ("admin", "admin"):
        return cl.User(
            identifier="admin", metadata={"role": "admin"}
        )
    else:
        return None
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?