add
This commit is contained in:
86
app/utils/JwtUtils.php
Normal file
86
app/utils/JwtUtils.php
Normal file
@@ -0,0 +1,86 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user