1 Star 0 Fork 0

向林 / kiri-jwt

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
JWTAuth.php 5.58 KB
一键复制 编辑 原始数据 按行查看 历史
向林 提交于 2022-09-10 18:36 . 变更
<?php
namespace Kiri\Jwt;
use Database\Model;
use Exception;
use Kiri;
use Kiri\Abstracts\Component;
use Kiri\Abstracts\Config;
use Kiri\Exception\ConfigException;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\UnencryptedToken;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\Constraint\StrictValidAt;
use Psr\Container\ContainerExceptionInterface;
use Kiri\Di\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
class JWTAuth extends Component implements JWTAuthInterface
{
/**
* @var string
*/
public string $iss = 'http://example.com';
/**
* @var string
*/
public string $aud = 'http://example.org';
/**
* @var string
*/
public string $jti = '4f1g23a12aa';
/**
* @var string
*/
private string $iat = \DateTimeImmutable::class;
/**
* @var array
*/
public array $nbf = [1, 'second'];
/**
* @var array|string[]
*/
public array $exp = [2, 'hour'];
/**
* @var string
*/
public string $claim = 'userId';
/**
* @var array|string[]
*/
public array $headers = ['foo' => 'bar'];
/**
* @var string|Model
*/
public string|Model $model;
/**
* @var Configuration
*/
private Configuration $configuration;
/**
* @var Builder|null
*/
private ?Builder $builder = NULL;
/**
* @var array
*/
public array $sso = [];
/**
* @param ContainerInterface $container
* @param array $config
* @throws Exception
*/
public function __construct(public ContainerInterface $container, array $config = [])
{
parent::__construct($config);
}
/**
*
* @throws ConfigException
*/
public function init(): void
{
$this->configuration = Configuration::forSymmetricSigner(new Sha256(),
InMemory::base64Encoded('mBC5v1sOKVvbdEitdSBenu59nfNfhwkedkJVNabosTw='));
$this->configuration->setValidationConstraints(
new SignedWith($this->configuration->signer(), $this->configuration->signingKey()),
new StrictValidAt(SystemClock::fromSystemTimezone())
);
$this->configure();
}
/**
* @throws ConfigException
*/
private function configure()
{
$config = Config::get('jwt', []);
if (empty($config)) {
return;
}
Kiri::configure($this, $config);
}
/**
* @param $key
* @param $value
* @return $this
*/
public function withHeader($key, $value): static
{
$this->headers[$key] = $value;
return $this;
}
/**
* @param int|string|null $value
* @return string
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function create(int|string $value = NULL): string
{
if (!$this->builder) {
$this->_create();
}
return $this->builder->withClaim($this->claim, $value)
->getToken($this->configuration->signer(), $this->configuration->signingKey())
->toString();
}
/**
* @param string $jwt
* @return string
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function refresh(string $jwt): string
{
$value = $this->getUniqueId($jwt);
return $this->create($value);
}
/**
* @param string $jwt
* @return UnencryptedToken
* @throws Exception
*/
public function parsing(string $jwt): UnencryptedToken
{
$parsing = $this->configuration->parser()->parse($jwt);
assert($parsing instanceof UnencryptedToken);
return $parsing;
}
/**
* @param string $jwt
* @return int|string
* @throws Exception
*/
public function getUniqueId(string $jwt): int|string
{
return $this->parsing($jwt)->claims()->get($this->claim);
}
/**
* @param string $jwt
* @param array $constraints
* @return bool|UnencryptedToken
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function validating(string $jwt, array $constraints = []): bool|UnencryptedToken
{
try {
$parse = $this->parsing($jwt);
if (empty($constraints)) {
$constraints = $this->configuration->validationConstraints();
}
$bool = $this->configuration->validator()->validate($parse, ...$constraints);
if (!$bool) {
return FALSE;
}
return $parse;
} catch (\Throwable $e) {
$this->logger->error($e->getMessage());
return FALSE;
}
}
/**
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function _create(): void
{
$this->builder = $this->configuration->builder()->issuedBy($this->iss)
->permittedFor($this->aud)->identifiedBy($this->jti)
->withClaim($this->claim, 1)
->withHeader('foo', 'bar');
$this->_date();
if (empty($this->headers) || !is_array($this->headers)) {
return;
}
foreach ($this->headers as $key => $header) {
$this->builder->withHeader($key, $header);
}
}
/**
* @return void
* @throws Exception
*/
private function _date(): void
{
/** @var \DateTimeImmutable $dateTimeImmutable */
$dateTimeImmutable = $this->container->make($this->iat, [date('Y-m-d H:i:s')]);
$this->builder->issuedAt($dateTimeImmutable);
if (count($this->nbf) == 2) {
[$nb1, $nb2] = $this->nbf;
$this->builder->canOnlyBeUsedAfter($dateTimeImmutable->modify('+' . $nb1 . ' ' . $nb2));
}
if (count($this->exp) == 2) {
[$nb1, $nb2] = $this->exp;
$this->builder->expiresAt($dateTimeImmutable->modify('+' . $nb1 . ' ' . $nb2));
}
}
}
1
https://gitee.com/dreamwithouttrace/kiri-jwt.git
git@gitee.com:dreamwithouttrace/kiri-jwt.git
dreamwithouttrace
kiri-jwt
kiri-jwt
master

搜索帮助