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.
 
 
 
 
 
 

61 lines
1.6 KiB

<?php
namespace app\api\service;
use Lcobucci\JWT\Parser;
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);
$builder = new Builder();
// 设置发行时间和过期时间
$now = time();
$token = $builder
->issuedAt($now) // iat: 发行时间
->expiresAt($now + config('jwt.token_ttl')) // exp: 过期时间
->withClaim('iss', 'your_issuer') // iss: 发行人
->withClaim('sub', 'your_subject') // sub: 主题
->withClaim('aud', 'your_audience'); // aud: 受众
// 添加自定义 Claims
foreach ($claims as $key => $value) {
$token = $token->withClaim($key, $value);
}
// 构建并签名 Token
$signedToken = $token->sign($signer, $key);
return (string) $signedToken;
}
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) {
// 处理异常
}
return [];
}
}