Skip to content

04 认证系统 Demo

对应文档: 04 认证与安全

Demo 目录: practice/04-auth-system

运行方式

bash
cd practice/04-auth-system
npm install
npm start    # Swagger: http://localhost:3001/api

交互测试流程

  1. 注册 POST /auth/register
    json
    { "email": "admin@example.com", "password": "pass123", "name": "Admin", "roles": ["admin"] }
  2. 登录 POST /auth/login → 获取 access_token
  3. Swagger 右上角 Authorize 填入 token
  4. 访问不同角色端点验证 RBAC:
    • GET /auth/admin-only → 仅 admin
    • GET /auth/editor-or-admin → editor 或 admin
    • GET /auth/any-user → 任意已认证用户

演示内容

  • LocalStrategy:用 email+password 登录
  • JwtStrategy:验证 Bearer Token
  • RolesGuard:基于 Reflector 读取 @Roles() 元数据
  • @CurrentUser() 自定义参数装饰器

运行测试

bash
npm test

NestJS 深度学习体系