Files
kiri-core/System/Jwt/JWTAuthMiddleware.php
T

52 lines
1.0 KiB
PHP
Raw Normal View History

2021-08-06 16:54:17 +08:00
<?php
declare(strict_types=1);
2021-08-11 01:04:57 +08:00
namespace Kiri\Jwt;
2021-08-06 16:54:17 +08:00
use Closure;
use Exception;
use HttpServer\Http\Request;
use HttpServer\IInterface\Middleware;
use Server\RequestInterface;
2021-08-11 01:04:57 +08:00
use Kiri\Kiri;
2021-08-06 16:54:17 +08:00
/**
* Class CoreMiddleware
2021-08-11 01:04:57 +08:00
* @package Kiri\Kiri\Route
2021-08-06 16:54:17 +08:00
* 跨域中间件
*/
class JWTAuthMiddleware implements Middleware
{
/** @var int */
public int $zOrder = 0;
/**
* @param Request $request
* @param Closure $next
* @return mixed
* @throws Exception
*/
public function onHandler(RequestInterface $request, Closure $next): mixed
{
$authorization = $request->header('Authorization');
if (empty($authorization)) {
throw new JWTAuthTokenException('JWT voucher cannot be empty.');
}
if (!str_starts_with($authorization, 'Bearer ')) {
throw new JWTAuthTokenException('JWT Voucher Format Error.');
}
$authorization = str_replace('Bearer ', '', $authorization);
2021-08-11 01:04:57 +08:00
$jwt = Kiri::app()->getJwt();
2021-08-06 16:54:17 +08:00
if (!$jwt->validator($authorization)) {
throw new JWTAuthTokenException('JWT Validator fail.');
}
return $next($request);
}
}