mengstack-website/guide/auth.md
2026-10-02 23:55:36 +08:00

108 lines
3.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 认证与授权
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 |
## 注册
```bash
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"
}'
```
响应:
```json
{
"code": 0,
"message": "success",
"data": {
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"refresh_token": "eyJhbGciOiJIUzI1NiIs...",
"expires_in": 7200
},
"trace_id": "abc-123-def"
}
```
## 登录
```bash
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>`:
```bash
curl http://localhost:2222/api/v1/profile \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
```
## 刷新 Token
Access Token 过期后,使用 Refresh Token 获取新的令牌对:
```bash
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 字符,邮箱格式校验