53 lines
1.6 KiB
PHP
53 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace app\api\behavior;
|
|
|
|
use think\Request;
|
|
use app\api\exception\ApiException;
|
|
use app\common\exception\EnumCode;
|
|
use think\Cache;
|
|
use Firebase\JWT\JWT;
|
|
use Firebase\JWT\Key;
|
|
use Firebase\JWT\SignatureInvalidException;
|
|
use Firebase\JWT\BeforeValidException;
|
|
use Firebase\JWT\ExpiredException;
|
|
use DomainException;
|
|
use Exception;
|
|
|
|
class AuthToken
|
|
{
|
|
public function run()
|
|
{
|
|
$header = Request::instance()->header();
|
|
|
|
$token = $header['token'];
|
|
|
|
if (empty($token)) {
|
|
throw new ApiException('token不存在', EnumCode::TokenNotExist);
|
|
}
|
|
|
|
try {
|
|
$decode = JWT::decode($token, new Key(config('jwt.key'), config('jwt.sign_type')));
|
|
|
|
$uid = $decode->data->uid;
|
|
|
|
$preFix = config('jwt.pre_fix') . $uid;
|
|
|
|
if (!Cache::get($preFix) || Cache::get($preFix) !== $token) {
|
|
throw new ApiException('签名验证失败', EnumCode::TokenSignInvalid);
|
|
}
|
|
|
|
} catch (SignatureInvalidException $e) {
|
|
throw new ApiException('签名不正确', EnumCode::TokenSignInvalid);
|
|
} catch (BeforeValidException $e) {
|
|
throw new ApiException('签名未到可用时间', EnumCode::TokenSignInvalid);
|
|
} catch (ExpiredException $e) {
|
|
throw new ApiException('签名过期', EnumCode::TokenSignInvalid);
|
|
} catch (DomainException $e) {
|
|
throw new ApiException('签名错误', EnumCode::TokenSignInvalid);
|
|
} catch (Exception $e) {
|
|
throw new ApiException($e->getMessage(), $e->getCode());
|
|
}
|
|
}
|
|
}
|