Files
game_server/docs/JWT认证使用说明.md

161 lines
3.3 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.

# JWT认证使用说明
## 概述
系统已从手动传递操作者信息的头部参数改为使用JWTJSON Web Token进行身份认证。这种方式更加安全、标准化并且符合REST API的最佳实践。
## 认证流程
### 1. 用户登录获取JWT令牌
```http
POST /api/auth/login
Content-Type: application/json
{
"username": "your_username",
"password": "your_password"
}
```
响应示例:
```json
{
"token": "eyJhbGciOiJIUzI1NiJ9...",
"userType": "AGENT",
"userId": 123,
"username": "your_username"
}
```
### 2. 使用JWT令牌调用受保护的接口
在请求头中添加 `Authorization` 头:
```http
POST /api/link/generate
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
Content-Type: application/json
{
"times": 10,
"perTimeQuantity": 5
}
```
## 链接生成接口
### 接口地址
`POST /api/link/generate`
### 请求头
- `Authorization: Bearer {JWT_TOKEN}` - 必需JWT认证令牌
- `Content-Type: application/json` - 必需
### 请求参数
```json
{
"times": 10, // 本次打脚本的次数
"perTimeQuantity": 5 // 每次打的数量
}
```
### 响应示例
```json
{
"batchId": 456,
"deductPoints": 50,
"expireAt": "2024-01-15T16:30:00",
"codeNos": ["ABC12345", "DEF67890", ...]
}
```
## 权限控制
### 代理用户
- 只能为自己生成链接
- 必须检查积分余额
- 生成链接时扣除相应积分
### 管理员用户
- 只能为自己生成链接
- 跳过积分检查
- 不扣除积分
## 安全特性
1. **JWT令牌验证**每个请求都会验证JWT令牌的有效性
2. **自动过期**JWT令牌有自动过期时间默认30分钟
3. **用户身份验证**从JWT中自动提取用户ID、用户类型等信息
4. **权限控制**:基于用户类型进行不同的业务逻辑处理
## 错误处理
### 常见错误
1. **缺少认证令牌**
```json
{
"error": "用户未认证"
}
```
2. **令牌无效或过期**
```json
{
"error": "JWT token validation failed"
}
```
3. **权限不足**
```json
{
"error": "非法操作者类型"
}
```
## 技术实现
### 核心组件
1. **JwtService**JWT令牌的生成和解析
2. **JwtAuthenticationFilter**自动处理JWT认证的Web过滤器
3. **SecurityConfig**Spring Security配置定义哪些接口需要认证
4. **LinkController**使用Spring Security上下文获取用户信息
### 认证流程
```
请求 → JwtAuthenticationFilter → JWT解析 → 创建认证对象 → Spring Security上下文 → 控制器获取用户信息
```
## 迁移说明
### 从旧版本迁移
如果您之前使用的是手动传递操作者信息的头部参数:
**旧方式(已废弃):**
```http
X-Operator-Id: 123
X-Operator-Type: AGENT
```
**新方式:**
```http
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
```
### 兼容性
- 旧的头参数方式已被完全移除
- 所有链接相关接口现在都需要JWT认证
- 确保在调用接口前先获取有效的JWT令牌
## 最佳实践
1. **令牌管理**客户端应妥善保存JWT令牌并在过期前刷新
2. **安全传输**始终使用HTTPS传输JWT令牌
3. **错误处理**:客户端应处理认证失败的情况,引导用户重新登录
4. **日志记录**:系统会自动记录所有认证相关的操作日志