这是一个最小但完整可运行的认证与登录 Demo,实现三类用户体系彼此独立、同自然人可拥有多种身份、同一设备可同时存在多个登录态、并支持多设备登录并存。
- 后端:Rust
axum - 数据库:MySQL(
sqlx异步驱动) - 密码哈希:
argon2(Argon2id) - 会话:DB session(
auth_sessions表落库),通过 Cookie 指向sid - 前端:React + TypeScript + Vite
后端为每类身份提供独立的:
- 认证(密码)表:
member_auth/community_staff_auth/platform_staff_auth - 资料(profile)表:
member_profile/community_staff_profile/platform_staff_profile - me 接口:
/api/member/me、/api/community-staff/me、/api/platform-staff/me
每个 me 只会校验对应 cookie(对应 session 的 auth_type),不会互相影响。
不同身份在同一浏览器/设备中使用不同 cookie 名:
member_sidcommunity_staff_sidplatform_staff_sid
因此同一设备同时登录三类身份不会互相“覆盖”。
注册时使用同一个 email:三类身份都会写入同一个共享自然人表 person,从而复用同一个 person_id。
同一 email 分别注册 Member/Community Staff/Platform Staff 后,/me 返回的 person.email 相同,但 profile 字段来自各自独立表。
每次登录都会生成一个新的不可预测 sid,写入 auth_sessions 表,并把该 sid 放入对应 cookie。
不同设备会携带不同的 sid,彼此不冲突;退出(logout)只会撤销当前 cookie 对应的那一条 session(仅当前身份类型)。
后端启动时会执行 CREATE TABLE IF NOT EXISTS:
person:共享自然人(email唯一)*_auth:三类身份独立密码体系(person_id主键外键)*_profile:三类身份独立资料体系auth_sessions:DB session,包含sid、auth_type、person_id、expires_at、revoked_at
确保本机已安装并运行 MySQL,并创建一个数据库(示例:rust_auth_demo)。
Demo 不使用 Docker;后端会直接连接你提供的 DATABASE_URL,并在该数据库内建表。
在项目根目录执行:
export DATABASE_URL='mysql://USER:PASSWORD@localhost:3306/rust_auth_demo'可选:
export BACKEND_PORT=3001
export FRONTEND_PORT=5173./start.sh前端会把请求 /api/* 通过 Vite proxy 转发到后端,因此无需额外配置 CORS。
- 注册
POST /api/member/registerPOST /api/community-staff/registerPOST /api/platform-staff/register
- 登录(创建 session + 设置 cookie)
POST /api/member/loginPOST /api/community-staff/loginPOST /api/platform-staff/login
- 退出(撤销当前 cookie 对应 session)
POST /api/member/logoutPOST /api/community-staff/logoutPOST /api/platform-staff/logout
- 查询当前登录资料
GET /api/member/meGET /api/community-staff/meGET /api/platform-staff/me
- Demo 为了最小可运行,使用 DB session(落库
sid)而非 JWT:减少 token 刷新/撤销复杂度。 - cookie 名按身份类型分离:确保同一浏览器可同时存在多个登录态。