php管理和接口
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.
 
 
 
 
 
 

40 lines
981 B

<?php
namespace app\api\service;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\Signer\Key\InMemory;
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 Token())->withClaim('id', $claims['id'])->withClaim('username', $claims['username']);
$token = $token->withExpiresAt(time() + config('jwt.token_ttl'));
return (string) $token->sign($signer, $key);
}
public function verifyToken(string $token): array
{
$parser = new Parser();
$token = $parser->parse((string) $token);
if ($token->verify(new Sha256(), InMemory::plainText($this->secret))) {
return $token->getClaims();
}
return [];
}
}