mengstack-website/guide/auth.md
SoftUnis ecb29e0aa4 初始化 MengStack 官方网站仓库
包含 VitePress 文档站完整源码及全新自定义首页设计:
- 自定义首页组件 (Home.vue):Hero + 终端动效 + 核心能力 + 架构展示 + 快速开始 + CTA
- 自定义 Layout.vue:首页/文档页布局切换
- 金铜色品牌主题样式
- 完整文档页面(指南、API、更新日志、演示、社区)
- SEO 配置(sitemap、robots、meta 标签)
2026-10-02 23:37:25 +08:00

3.6 KiB
Raw Blame History

认证与授权

MengStack 内置完整的认证授权系统,基于 JWT 双 Token 机制。

认证流程

┌────────┐     POST /auth/register     ┌────────┐
│ Client │ ──────────────────────────→ │ Server │
│        │ ←────────────────────────── │        │
│        │   { access_token, refresh }  │        │
│        │                              │        │
│        │     POST /auth/login         │        │
│        │ ──────────────────────────→ │        │
│        │ ←────────────────────────── │        │
│        │   { access_token, refresh }  │        │
│        │                              │        │
│        │   GET /api/v1/profile        │        │
│        │   Authorization: Bearer xxx  │        │
│        │ ──────────────────────────→ │        │
│        │ ←────────────────────────── │        │
│        │   { user data }              │        │
│        │                              │        │
│        │   POST /auth/refresh         │        │
│        │   { refresh_token }          │        │
│        │ ──────────────────────────→ │        │
│        │ ←────────────────────────── │        │
│        │   { new token pair }         │        │
└────────┘                              └────────┘

API 端点

端点 方法 说明 认证
/api/v1/auth/register POST 用户注册 无
/api/v1/auth/login POST 用户登录 无
/api/v1/auth/refresh POST 刷新令牌 无
/api/v1/password POST 修改密码 Bearer
/api/v1/profile GET 获取当前用户 Bearer

注册

curl -X POST http://localhost:2222/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "username": "johndoe",
    "nickname": "John Doe",
    "password": "securepass123"
  }'

响应:

{
  "code": 0,
  "message": "success",
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIs...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIs...",
    "expires_in": 7200
  },
  "trace_id": "abc-123-def"
}

登录

curl -X POST http://localhost:2222/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "securepass123"
  }'

使用 Access Token

在请求头中携带 Authorization: Bearer <access_token>:

curl http://localhost:2222/api/v1/profile \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."

刷新 Token

Access Token 过期后,使用 Refresh Token 获取新的令牌对:

curl -X POST http://localhost:2222/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "eyJhbGciOiJIUzI1NiIs..."
  }'

安全特性

  • 密码哈希:使用 bcrypt 加密存储,永不明文
  • 双 Token:Access Token 短期有效(2h),Refresh Token 长期有效(7d)
  • Token 轮换:每次刷新都生成全新的令牌对
  • 验证约束:用户名 3-64 字符,密码 8-128 字符,邮箱格式校验