实现过程:
namespace App\Server;
use Firebase\JWT\JWT;
class single
{
// 私有的静态属性
private static $instance;
// 定义私有的key(令牌)
private $key;
// 定义私有的jwt加密算法
private $algorithm;
// 定义私有声明标识JWT的签发人
private $issuer;
// 定义私有声明 标识JWT的接收对象
private $audience;
// 私有的构造函数
private function __construct()
{
$this->key=config('jwt.key');
$this->algorithm=config('jwt.algorithm');
$this->issuer=config('jwt.issuer');
$this->audience=config('jwt.audience');
}
// 私有的克隆方法
private function __clone()
{
// TODO: Implement __clone() method.
}
// 公有的静态属性
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 加密过程
* @param $user
* @return string
*/
public function encode($user)
{
$now = time();
$token =[
'iss' => $this->issuer,
'aud' =>$this->audience,
'iat' => $now,
'nbf' => $now,
'id'=>$user['id']
];
return JWT::encode($token, $this->key, $this->algorithm);
}
/**
* 解密过程
* @param $token
* @return array
*/
public function decode($token)
{
$payload = JWT::decode($token,$this->key, $this->algorithm);
$now = time();
$token = [
'iss' => 'http://example.org',
'aud' => 'http://example.com',
'iat' => $now,
'nbf' => $now,
];
return array_merge((array) $token, $payload);
}
以上实例仅供参考若有更好的方法可自行选择,让我们打开脑洞尽情发挥自己的才能,让我们的技术更加绚丽多彩....