Initial commit
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace app\mzl\modules\jwt\middleware;
|
||||
|
||||
use ReflectionClass;
|
||||
use Webman\Http\Request;
|
||||
use Webman\Http\Response;
|
||||
use Webman\MiddlewareInterface;
|
||||
use app\mzl\modules\jwt\service\JwtService;
|
||||
|
||||
class JwtMiddleware implements MiddlewareInterface
|
||||
{
|
||||
|
||||
protected $jwtService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->jwtService = new JwtService();
|
||||
}
|
||||
|
||||
public function process(Request $request, callable $handler): Response
|
||||
{
|
||||
// 通过反射获取控制器
|
||||
$controller = new ReflectionClass($request->controller);
|
||||
$noNeedJwt = $controller->getDefaultProperties()['noNeedJwt'] ?? [];
|
||||
|
||||
// 除外
|
||||
if (in_array($request->action, $noNeedJwt)) {
|
||||
|
||||
return $handler($request);
|
||||
} else {
|
||||
try {
|
||||
$authHeader = $request->header('Authorization');
|
||||
|
||||
if (!$authHeader || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
|
||||
$body = [
|
||||
'status' => 'error',
|
||||
'code' => 401,
|
||||
'message' => '未授权',
|
||||
'data' => [],
|
||||
];
|
||||
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||
}
|
||||
|
||||
$token = $matches[1];
|
||||
|
||||
$request->user = $this->jwtService->verifyToken($token);
|
||||
|
||||
// 验证权限 -- start
|
||||
// $user = \app\mzl\modules\permission\model\User::find($request->user->user_id);
|
||||
// if (!$user || !$user->hasPermission($request->path())) {
|
||||
// $body = [
|
||||
// 'status' => 'error',
|
||||
// 'code' => 403,
|
||||
// 'message' => '无权限访问',
|
||||
// 'data' => [],
|
||||
// ];
|
||||
// return response(json_encode($body, JSON_UNESCAPED_UNICODE), 403, ['Content-Type' => 'application/json']);
|
||||
// }
|
||||
// 验证权限 -- end
|
||||
} catch (\Throwable $e) {
|
||||
$body = [
|
||||
'status' => 'error',
|
||||
'code' => 401,
|
||||
'message' => $e->getMessage(),
|
||||
'data' => [],
|
||||
];
|
||||
return response(json_encode($body, JSON_UNESCAPED_UNICODE), 401, ['Content-Type' => 'application/json']);
|
||||
}
|
||||
|
||||
return $handler($request);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace app\mzl\modules\jwt\service;
|
||||
|
||||
use Firebase\JWT\JWT as FirebaseJWT;
|
||||
use Firebase\JWT\Key;
|
||||
use support\exception\BusinessException;
|
||||
|
||||
class JwtService
|
||||
{
|
||||
protected $secretKey;
|
||||
protected $algorithm;
|
||||
protected $issuer;
|
||||
protected $expiration;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->secretKey = getenv('JWT_SECRET_KEY') ?: 'default_secret_key';
|
||||
$this->algorithm = getenv('JWT_ALGORITHM') ?: 'HS256';
|
||||
$this->issuer = getenv('JWT_ISSUER') ?: 'domain.com';
|
||||
$this->expiration = (int)(getenv('JWT_EXPIRATION') ?: 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 JWT 令牌
|
||||
*
|
||||
* @param array $payload
|
||||
* @return string
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function generateToken(array $payload): string
|
||||
{
|
||||
$defaultPayload = [
|
||||
'iss' => $this->issuer,
|
||||
'iat' => time(),
|
||||
'nbf' => time(),
|
||||
'exp' => time() + $this->expiration,
|
||||
];
|
||||
|
||||
$payload = array_merge($defaultPayload, $payload);
|
||||
|
||||
try {
|
||||
return FirebaseJWT::encode($payload, $this->secretKey, $this->algorithm);
|
||||
} catch (\Exception $e) {
|
||||
throw new BusinessException("令牌生成失败:" . $e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证 JWT 令牌
|
||||
*
|
||||
* @param string $token
|
||||
* @return object
|
||||
* @throws BusinessException
|
||||
*/
|
||||
public function verifyToken(string $token)
|
||||
{
|
||||
try {
|
||||
return FirebaseJWT::decode($token, new Key($this->secretKey, $this->algorithm));
|
||||
} catch (\Firebase\JWT\ExpiredException $e) {
|
||||
throw new BusinessException('令牌已过期', 401);
|
||||
} catch (\Firebase\JWT\SignatureInvalidException $e) {
|
||||
throw new BusinessException('无效的令牌签名', 401);
|
||||
} catch (\Firebase\JWT\BeforeValidException $e) {
|
||||
throw new BusinessException('令牌尚未生效', 401);
|
||||
} catch (\Exception $e) {
|
||||
throw new BusinessException('令牌验证失败:' . $e->getMessage(), 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user