API接口-authtoken、redis

This commit is contained in:
2026-03-19 18:07:18 +08:00
parent 019b536a89
commit 4f61c9d7fc
11 changed files with 303 additions and 3 deletions

View File

@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace app\common\library;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
/**
* Agent 鉴权 JWT 工具
*/
class AgentJwt
{
public const ALG = 'HS256';
/**
* 生成 JWT authtoken
* @param array $payload agent_id, channel_id, admin_id 等
* @param int $expire 有效期(秒)
*/
public static function encode(array $payload, int $expire = 86400): string
{
$now = time();
$payload['iat'] = $now;
$payload['exp'] = $now + $expire;
$secret = self::getSecret();
return JWT::encode($payload, $secret, self::ALG);
}
/**
* 解析并验证 JWT返回 payload
* @return array payload失败返回空数组
*/
public static function decode(string $token): array
{
if ($token === '') {
return [];
}
try {
$secret = self::getSecret();
$decoded = JWT::decode($token, new Key($secret, self::ALG));
return (array) $decoded;
} catch (ExpiredException|SignatureInvalidException|\Throwable) {
return [];
}
}
/**
* 验证 JWT 是否有效
*/
public static function verify(string $token): bool
{
return !empty(self::decode($token));
}
private static function getSecret(): string
{
$secret = config('buildadmin.agent_auth.jwt_secret', '');
if ($secret === '') {
$secret = config('buildadmin.token.key', '');
}
return $secret;
}
}