chainlit 对于auth 上支持了多种模式,比如基于用户密码的,基于header的以及基于oauth 的
对于认证的用户就可以通过session 变量获取信息了,方便后续使用

集中模式说明

  • 用户密码模式
    此模式比较简单,核心是按需返回需要的数据,此处可以是基于db 的也可以是基于api 的,使用如下
from typing import Optional
import chainlit as cl
 
@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", "provider": "credentials"}
        )
    else:
        return None
header 模式
比较适合委托认证到代理服务中,使用如下
@cl.header_auth_callback
def header_auth_callback(headers: Dict) -> Optional[cl.User]:
  # Verify the signature of a token in the header (ex: jwt token)
  # or check that the value is matching a row from your database
  if headers.get("test-header") == "test-value":
    return cl.User(identifier="admin", metadata={"role": "admin", "provider": "header"})
  else:
    return None
oauth 模式
具体需要配置一些oauth 信息,包含了环境变量以及callback
@cl.oauth_callback
def oauth_callback(
  provider_id: str,
  token: str,
  raw_user_data: Dict[str, str],
  default_user: cl.User,
) -> Optional[cl.User]:
  return default_user
import chainlit as cl

业务集成

  • user 的基本信息
    如下基本用户密码认证模式的,我们需要包含的是identifier,metadata,实际上还有一个可选的display_name metadata 是一个字典可以存储各类数据,一般我们会存储一些角色或者其他信息,对于开启持久化的会存储到db 的users 中,注意此数据会在每次登陆的时候进行更新
from typing import Optional
import chainlit as cl
@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", "provider": "credentials"}
        )
    else:
        return None
import chainlit as cl
  • session 使用
app_user = cl.user_session.get("user")

说明

对于开启认证的,是需要一个CHAINLIT_AUTH_SECRET的,这个可以通过chainlit create-secret 生成,使用了chainlit 提供的
认证模式可以更好的基于chainlit 快速开发chatapp 应用

参考资料

https://docs.chainlit.io/authentication/overview