php 单例模式封装jwt的使用

实现过程:
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);

    }

以上实例仅供参考若有更好的方法可自行选择,让我们打开脑洞尽情发挥自己的才能,让我们的技术更加绚丽多彩....

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值