You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.1 KiB
47 lines
1.1 KiB
<?php
|
|
namespace app\api\service;
|
|
|
|
use Lcobucci\JWT\Builder;
|
|
use Lcobucci\JWT\Signer\Hmac\Sha256;
|
|
use Lcobucci\JWT\Signer\Key\InMemory;
|
|
use Lcobucci\JWT\Token;
|
|
|
|
class JWTService
|
|
{
|
|
private $secret;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->secret = config('jwt.secret');
|
|
}
|
|
|
|
public function createToken(array $claims): string
|
|
{
|
|
$signer = new Sha256();
|
|
$key = InMemory::plainText($this->secret);
|
|
|
|
$token = (new Builder())->issuedNow()->canOnlyBeUsedAfter(0)->expiresAt(time() + config('jwt.token_ttl'));
|
|
|
|
foreach ($claims as $key => $value) {
|
|
$token = $token->withClaim($key, $value);
|
|
}
|
|
|
|
return (string) $token->sign($signer, $key);
|
|
}
|
|
|
|
public function verifyToken(string $token): array
|
|
{
|
|
try {
|
|
$parser = new \Lcobucci\JWT\Parser();
|
|
$token = $parser->parse($token);
|
|
|
|
if ($token->verify(new Sha256(), InMemory::plainText($this->secret))) {
|
|
return $token->getClaims();
|
|
}
|
|
} catch (\Exception $e) {
|
|
// Handle exception
|
|
}
|
|
|
|
return [];
|
|
}
|
|
}
|