87 lines
1.8 KiB
PHP
87 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace app\utils;
|
|
use Firebase\JWT\JWT;
|
|
use Firebase\JWT\Key;
|
|
|
|
class JwtUtils
|
|
{
|
|
private string $secret = "f4e2e52034348f86b67cde581c0f9eb5";
|
|
private int $expire = 604800; // 单位:秒
|
|
private string $header = "token";
|
|
|
|
public function __construct()
|
|
{
|
|
$this->secret = base64_decode($this->secret);
|
|
}
|
|
|
|
|
|
/**
|
|
* 生成 JWT Token
|
|
*/
|
|
public function generateToken($userId, string $type): string
|
|
{
|
|
$now = time();
|
|
$payload = [
|
|
'sub' => (string)$userId,
|
|
'type' => $type,
|
|
'iat' => $now,
|
|
'exp' => $now + $this->expire
|
|
];
|
|
|
|
return JWT::encode($payload, $this->secret, 'HS512');
|
|
}
|
|
|
|
/**
|
|
* 从 token 中解析出 Claims
|
|
*/
|
|
public function getClaimByToken(string $token): ?object
|
|
{
|
|
try {
|
|
return JWT::decode($token, new Key($this->secret, 'HS512'));
|
|
} catch (\Exception $e) {
|
|
error_log('Token 验证失败: ' . $e->getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 判断 token 是否过期(通过传入的 exp 字段)
|
|
*/
|
|
public function isTokenExpired(int $exp): bool
|
|
{
|
|
return $exp < time();
|
|
}
|
|
|
|
// Getter/Setter
|
|
public function getSecret(): string
|
|
{
|
|
return $this->secret;
|
|
}
|
|
|
|
public function getExpire(): int
|
|
{
|
|
return $this->expire;
|
|
}
|
|
|
|
public function getHeader(): string
|
|
{
|
|
return $this->header;
|
|
}
|
|
|
|
public function setSecret(string $secret): void
|
|
{
|
|
$this->secret = $secret;
|
|
}
|
|
|
|
public function setExpire(int $expire): void
|
|
{
|
|
$this->expire = $expire;
|
|
}
|
|
|
|
public function setHeader(string $header): void
|
|
{
|
|
$this->header = $header;
|
|
}
|
|
}
|