侧边栏壁纸
博主昵称
404

  • 累计撰写 17 篇文章
  • 累计收到 0 条评论

JWT验证

404
404
2022-07-29 / 0 评论 / 25 阅读 / 正在检测是否收录...

安装
composer require lcobucci/jwt=3.3.3

<?php
namespace app\api\lib;

use think\facade\Db;

use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Hmac\Sha256;

class Jwt
{
    private $token = '';
    private $username = '';//当前用户标识
    private static $instance = null;


    private function __construct()
    {
        $this->token = request()->param('token');
        $this->username = request()->param('username');
        if($this->token != "" && $this->token != null){
            $this->token = (new Parser())->parse($this->token);
            $this->username = $this->token->getClaim('username'); 
        }
    }

    //入口
    public static function getInstance()
    {
        if(!self::$instance instanceof self){
            self::$instance = new self();
        }
        return self::$instance;
    }

    //生成Token
    private function createToken()
    {
        $configJwt = $this->getSystemJwt();
        $time = time();
        $signer = new Sha256();
        $this->token = (new Builder())
            ->issuedBy('http://live.com/')//发行者
            ->identifiedBy('live',true)//id
            ->issuedAt($time)//发行时间
            ->canOnlyBeUsedAfter($time + 0)//生效时间
            ->expiresAt($time + $configJwt['content']['jwk_time'])//过期时间
            ->withClaim('username', $this->username)//配置字段
            ->getToken($signer, new Key($configJwt['content']['jwk_key']));//创建token
    }

    //验证token
    public function checkToken() {
        $configJwt = $this->getSystemJwt();
        $time = time();
        $data = new ValidationData();
        $data->setIssuer('http://live.com/'); //发行者
        $data->setId('live'); //id
        $data->setCurrentTime($time + 0);
        $signer = new Sha256();
        if($this->token->verify($signer, $configJwt['content']['jwk_key'])===true && $this->token->validate($data)===true){
            //判断用户状态
            $user = Db::name('user')->where('user', $this->username)->find();
            if($user){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public function setToken() {
        $this->createToken();
        return $this;
    }

    public function getToken() {
        // 当前token为对象类型
        return $this->token;
    }

    public function getSystemJwt()
    {
        $jwt = Db::name('system')->where('name','JWT')->find();
        $jwt['content']  = json_decode($jwt['content'],true);
        return $jwt;
    }

}


调用
生成token
use app\api\lib\Jwt as JwtAuth;
$token = JwtAuth::getInstance()->setToken()->getToken()->__toString();

验证token
 $result = JwtAuth::getInstance()->checkToken();
 dd($result);
0

评论 (0)

取消