You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
1.7 KiB
82 lines
1.7 KiB
9 months ago
|
<?php
|
||
|
|
||
|
namespace service;
|
||
|
|
||
|
use think\Request;
|
||
|
use think\Config;
|
||
|
use service\JsonService;
|
||
|
use Firebase\JWT\JWT;
|
||
|
|
||
|
class JwtService
|
||
|
{
|
||
|
/**
|
||
|
* token
|
||
|
* @var string
|
||
|
*/
|
||
|
protected $token;
|
||
|
|
||
|
protected $tokenKey;
|
||
|
|
||
|
public function __construct($channel = "wap")
|
||
|
{
|
||
|
switch ($channel) {
|
||
|
case "kefu":
|
||
|
$this->tokenKey = Config::get('token.kefu_key');
|
||
|
break;
|
||
|
case "wap":
|
||
|
default:
|
||
|
$this->tokenKey = Config::get("token.app_key");
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 获取token
|
||
|
* @param int $id
|
||
|
* @param string $type
|
||
|
* @param array $params
|
||
|
* @return array
|
||
|
*/
|
||
|
public function getToken(int $id, array $params = [])
|
||
|
{
|
||
|
$host = Request()->host();
|
||
|
$time = time();
|
||
|
$exp_time = strtotime('+ 30day');
|
||
|
$params += [
|
||
|
'iss' => $host,
|
||
|
'aud' => $host,
|
||
|
'iat' => $time,
|
||
|
'nbf' => $time,
|
||
|
'exp' => $exp_time
|
||
|
];
|
||
|
$params['jti'] = compact('id');
|
||
|
$token = JWT::encode($params, $this->tokenKey);
|
||
|
|
||
|
return $token;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 解析token
|
||
|
* @param string $jwt
|
||
|
* @return array
|
||
|
*/
|
||
|
public function parseToken(string $jwt)
|
||
|
{
|
||
|
$this->token = $jwt;
|
||
|
list($headb64, $bodyb64, $cryptob64) = explode('.', $this->token);
|
||
|
$payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
|
||
|
return $payload->jti->id;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* 验证token
|
||
|
*/
|
||
|
public function verifyToken()
|
||
|
{
|
||
|
JWT::$leeway = 60;
|
||
|
JWT::decode($this->token, $this->tokenKey, array('HS256'));
|
||
|
|
||
|
$this->token = null;
|
||
|
}
|
||
|
}
|