9.6 KiB
9.6 KiB
Token认证缓存服务使用指南
概述
TokenAuthService是一个专为Laravel Sanctum设计的高性能认证缓存服务,通过智能缓存机制大大减少数据库查询次数,提升API响应速度。
核心特性
1. 智能缓存策略
- 动态缓存时间:根据token剩余有效期自动调整缓存时间
- 健康检查:自动检测缓存可用性,故障时自动回退到数据库
- 多缓存驱动支持:支持Redis、文件缓存等多种缓存驱动
2. 性能优化
- 减少数据库查询:相同token的重复验证直接从缓存获取
- 自动过期管理:缓存时间不超过token剩余有效期
- 异常恢复:缓存失败时自动降级到数据库验证
3. 安全设计
- Token哈希存储:使用SHA256对token进行哈希后作为缓存键
- 自动清理:登出时自动清空相关缓存
- 状态验证:验证用户状态(is_active, deleted等)
架构设计
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ HTTP请求 │───▶│ AdminApiAuth │───▶│ TokenAuthService│
│ │ │ Middleware │ │ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
┌─────────────────────────┼─────────────────────────┐
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ 缓存层检查 │ │ 数据库验证 │ │ 缓存管理 │
│ (Redis/File) │ │ (Sanctum) │ │ (清理/统计) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
主要组件
1. TokenAuthService 认证服务
位置: app/Services/Auth/TokenAuthService.php
核心方法:
validateTokenAndGetUser()
验证token并获取用户信息,支持缓存加速:
public function validateTokenAndGetUser(string $token, string $guard = 'sanctum'): ?User
工作流程:
- 检查缓存健康状态
- 尝试从缓存获取用户信息
- 缓存未命中时从数据库验证
- 成功验证后将结果存入缓存
calculateCacheTime()
智能计算缓存时间:
protected function calculateCacheTime(string $token): int
缓存策略:
- 基于token剩余有效期的1/4作为缓存时间
- 最小缓存时间:1分钟
- 最大缓存时间:30分钟
- 无过期时间token:默认5分钟
clearTokenCache()
清空指定token的缓存:
public function clearTokenCache(string $token): bool
clearCacheOnLogout()
登出时清空缓存:
public function clearCacheOnLogout(User $user, ?string $currentToken = null): int
2. AdminApiAuthenticate 中间件
位置: app/Http/Middleware/AdminApiAuthenticate.php
功能:
- 集成TokenAuthService进行认证
- 提取请求中的Bearer Token
- 认证失败时返回标准化401响应
3. AuthController 控制器扩展
新增方法:
clearAuthCache()- 缓存清理管理getCacheStats()- 缓存统计信息
使用方法
1. 基本使用
在控制器中注入服务:
<?php
namespace App\Http\Controllers;
use App\Services\Auth\TokenAuthService;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function __construct(
protected TokenAuthService $tokenAuthService
) {}
public function someMethod(Request $request)
{
$token = $request->bearerToken();
$user = $this->tokenAuthService->validateTokenAndGetUser($token);
if (!$user) {
return response()->json(['error' => 'Invalid token'], 401);
}
// 继续业务逻辑...
}
}
2. 中间件使用
在路由中使用自定义认证中间件:
// routes/admin.php
Route::middleware('admin.auth')->group(function () {
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
});
3. 缓存管理
清空当前token缓存
curl -X DELETE http://localhost:8000/admin/auth/cache \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{"type": "current"}'
清空用户所有token缓存
curl -X DELETE http://localhost:8000/admin/auth/cache \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{"type": "user"}'
清空所有认证缓存(管理员)
curl -X DELETE http://localhost:8000/admin/auth/cache \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{"type": "all"}'
获取缓存统计
curl -X GET http://localhost:8000/admin/auth/cache/stats \
-H "Authorization: Bearer YOUR_TOKEN"
4. 登出时自动清理
在AuthController中,登出方法已自动集成缓存清理:
public function logout(Request $request): JsonResponse
{
$user = $request->user();
$currentToken = $request->bearerToken();
// 清空当前token的缓存
if ($currentToken) {
$this->tokenAuthService->clearTokenCache($currentToken);
}
// 删除当前使用的token
$user->currentAccessToken()->delete();
return $this->Success(['message' => '登出成功']);
}
配置说明
1. 缓存配置
使用Redis缓存(推荐)
CACHE_STORE=redis
REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=
使用文件缓存(开发环境)
CACHE_STORE=file
2. 缓存参数调整
在TokenAuthService中可以调整缓存参数:
class TokenAuthService
{
const DEFAULT_CACHE_MINUTES = 5; // 默认缓存时间
const MAX_CACHE_MINUTES = 30; // 最大缓存时间
const CACHE_PREFIX = 'auth_token:'; // 缓存键前缀
}
测试和验证
1. Web测试界面
访问测试页面查看系统状态:
http://localhost:8000/test-auth-cache
2. API测试
缓存健康检查
curl -X GET http://localhost:8000/admin/auth/cache/test \
-H "Authorization: Bearer YOUR_TOKEN"
响应示例:
{
"success": true,
"message": "缓存测试结果",
"data": {
"cache_prefix": "auth_token:",
"default_cache_minutes": 5,
"max_cache_minutes": 30,
"cache_available": true,
"cache_health": true,
"cache_store": "file"
}
}
3. 性能对比
无缓存(每次数据库查询):
- 单次认证: ~50-100ms
- 100次认证: ~5-10秒
有缓存(命中缓存):
- 单次认证: ~1-5ms
- 100次认证: ~0.1-0.5秒
性能提升: 10-20倍
监控和日志
1. 日志记录
系统会自动记录以下日志:
- 缓存命中:
Log::debug('Token认证使用缓存') - 缓存存储:
Log::debug('Token认证结果已缓存') - 缓存失败:
Log::warning('缓存读取失败') - 健康检查:
Log::error('缓存健康检查失败')
2. 监控指标
可以通过缓存统计API监控:
- 缓存驱动类型
- 缓存可用性状态
- 缓存健康状态
- 缓存配置参数
故障排查
1. Redis连接问题
现象: 系统报Redis连接错误 解决方案:
- 确认Redis服务正在运行:
redis-cli ping - 检查Redis配置:
.env文件中的Redis参数 - 验证网络连接: 防火墙设置
临时方案: 切换到文件缓存
CACHE_STORE=file
2. 缓存不生效
现象: 每次都查询数据库 排查步骤:
- 检查缓存健康状态:
/admin/auth/cache/stats - 查看错误日志:
storage/logs/laravel.log - 验证缓存目录权限:
storage/framework/cache
3. 性能问题
现象: API响应慢 优化建议:
- 使用Redis替代文件缓存
- 调整缓存时间参数
- 监控缓存命中率
最佳实践
1. 缓存策略
- 生产环境使用Redis
- 开发环境可使用文件缓存
- 定期清理过期缓存
2. 安全考虑
- Token使用SHA256哈希存储
- 用户状态变更时及时清理缓存
- 敏感操作不依赖缓存
3. 性能优化
- 合理设置缓存时间
- 监控缓存命中率
- 避免缓存雪崩
扩展功能
1. 自定义缓存键策略
protected function getTokenCacheKey(string $token): string
{
// 可以添加用户ID等信息到缓存键
return self::CACHE_PREFIX . hash('sha256', $token);
}
2. 缓存预热
public function warmupCache(User $user, string $token): void
{
$cacheKey = $this->getTokenCacheKey($token);
$cacheMinutes = $this->calculateCacheTime($token);
Cache::put($cacheKey, $user, now()->addMinutes($cacheMinutes));
}
3. 缓存统计增强
public function getCacheHitRate(): float
{
// 实现缓存命中率统计
return $this->cacheHits / ($this->cacheHits + $this->cacheMisses);
}
维护者: 开发团队
更新时间: 2024-12
版本: v1.0