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

51 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;
2021-08-19 11:00:04 +08:00
use Http\Route\MiddlewareAbstracts;
2021-08-06 16:54:17 +08:00
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
* 跨域中间件
*/
2021-08-19 11:00:04 +08:00
class JWTAuthMiddleware extends MiddlewareAbstracts
2021-08-06 16:54:17 +08:00
{
/** @var int */
public int $zOrder = 0;
/**
2021-08-28 00:51:27 +08:00
* @param RequestInterface $request
2021-08-06 16:54:17 +08:00
* @param Closure $next
* @return mixed
* @throws Exception
*/
public function onHandler(RequestInterface $request, Closure $next): mixed
{
2021-08-28 00:51:27 +08:00
$authorization = $request->getHeaderLine('Authorization');
2021-08-06 16:54:17 +08:00
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);
}
}