API接口-优化/创建保存jwt
This commit is contained in:
48
app/common/library/PlayxInboundJwt.php
Normal file
48
app/common/library/PlayxInboundJwt.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* PlayX / 合作方回调:校验 Authorization: Bearer JWT(HS256)
|
||||
*/
|
||||
class PlayxInboundJwt
|
||||
{
|
||||
public const ALG = 'HS256';
|
||||
|
||||
/**
|
||||
* 从 Authorization 头解析 Bearer token 并校验签名与有效期
|
||||
*/
|
||||
public static function verifyBearer(string $authorizationHeader, string $secret): bool
|
||||
{
|
||||
if ($secret === '') {
|
||||
return false;
|
||||
}
|
||||
$token = self::extractBearer($authorizationHeader);
|
||||
if ($token === '') {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
JWT::decode($token, new Key($secret, self::ALG));
|
||||
|
||||
return true;
|
||||
} catch (ExpiredException|SignatureInvalidException|\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function extractBearer(string $authorizationHeader): string
|
||||
{
|
||||
if (preg_match('/Bearer\s+(\S+)/i', $authorizationHeader, $m)) {
|
||||
return $m[1];
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user