chainlit 集成外部认证的方法

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

业务集成

  • 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
  • session 使用
app_user = cl.user_session.get("user")

说明

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

参考资料

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

posted on   荣锋亮  阅读(100)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2022-08-31 主机网络限速+测速工具
2022-08-31 nginx proxy_pass 包含路径问题
2022-08-31 windows jenkins openssh 集成问题
2020-08-31 orika java bean 转换工具试用
2020-08-31 graalvm js 内置commonjs 模式试用
2020-08-31 graalvm js 与java 类型转换的一些方法
2019-08-31 haproxy 2.0 dataplaneapi docker 镜像

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示