When you create a Chainlit app, you can choose to enable authentication. This will add a login page to your app. Only authenticated users will be able to access your app.

The authentication system is flexible with callbacks. This enables you to adapt the authentication to your needs.

Each Chainlit app has an independent authentication system. It has nothing to do with Chainlit cloud authentication.

Configuration

To enable authentication, you need to create one of the authentication callbacks in your app, depending on your chosen authentication method. You can add multiple callbacks to enable multiple authentication methods.

You also need to define the CHAINLIT_AUTH_SECRET environment variable. This is a secret string that is used to sign the authentication tokens. You can change it at any time, but it will log out all users. You can easily generate it using chainlit create-secret.

The callbacks take an input that depends on the authentication method, and they return an optional AppUser object. If the callback returns None, the authentication is considered as failed. If it returns an AppUser object, the authentication is considered as successful. The AppUser object is then stored in the session.

The callback can be sync or async, the annotation can handle either.

Make sure each user has a unique username to prevent them from sharing their session.

Get the current authenticated user

You can access the current authenticated user through the user_session.

@cl.on_chat_start
async def on_chat_start():
    app_user = cl.user_session.get("user")
    await cl.Message(f"Hello {app_user.username}").send()