Files
docs/thinkphp/app/middleware/AdminAuth.php
cenzuhai 3a04eede84 feat: 初始化进销存数据开放平台项目
初始化完整的前后端项目结构,包含ThinkPHP后端API服务和Next.js前端管理系统,添加基础配置、中间件、模型、路由等核心代码,以及项目文档和静态资源。
2026-07-08 17:48:00 +08:00

55 lines
1.3 KiB
PHP

<?php
namespace app\middleware;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Request;
use think\Response;
/**
* 管理员认证中间件
*/
class AdminAuth
{
/**
* 处理请求
*/
public function handle(Request $request, \Closure $next)
{
$token = $request->header('Authorization');
if (empty($token)) {
return json([
'code' => 401,
'msg' => '未提供认证令牌'
], 401);
}
// 移除 "Bearer " 前缀
if (strpos($token, 'Bearer ') === 0) {
$token = substr($token, 7);
}
try {
$secretKey = env('jwt.secret_key', 'your-super-secret-key-change-in-production-32chars!');
$algorithm = env('jwt.algorithm', 'HS256');
$decoded = JWT::decode($token, new Key($secretKey, $algorithm));
$payload = (array)$decoded;
// 将管理员信息存入请求
$request->adminUser = [
'id' => $payload['sub'],
'username' => $payload['username'],
];
return $next($request);
} catch (\Exception $e) {
return json([
'code' => 401,
'msg' => '无效的认证令牌'
], 401);
}
}
}