JWT使用
作者:互联网
JWT使用
标签(空格分隔): php
安装
composer require lcobucci/jwt
使用
<?php
namespace app\common\auth;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
class JwtAuth
{
private static $instance;
private $token;
private $decodeToken;
private $iis = 'web.tp5.cn';
private $aud = 'web.tp5.cn';
private $uid;
private $configId;
private $secret = 'web.tp5.cn';
private function __construct() {}
public static function getInstance()
{
if (!self::$instance) self::$instance = new self();
return self::$instance;
}
private function __clone() {}
public function setUid($uid)
{
$this->uid = $uid;
return $this;
}
public function setConfigId($configId)
{
$this->configId = $configId;
return $this;
}
public function getToken()
{
return (string)$this->token;
}
public function setToken($token)
{
$this->token = $token;
return $this;
}
public function encode()
{
$time = time();
$this->token = (new Builder())->setHeader('alg', 'HS256')
->setIssuedAt($this->iis)
->setAudience($this->aud)
->setIssuedAt($time)
->setExpiration($time + 120)
->set('uid', $this->uid)
->set('configId', $this->configId)
->sign(new Sha256(), $this->secret)
->getToken();
return $this;
}
public function decode()
{
if (!$this->decodeToken) {
$this->decodeToken = (new Parser())->parse((string) $this->token);
$this->uid = $this->decodeToken->getClaim('uid');
$this->configId = $this->decodeToken->getClaim('configId');
}
return $this->decodeToken;
}
public function verify()
{
return $this->decode()->verify(new Sha256(), $this->secret);
}
public function validate()
{
$data = new ValidationData();
$data->setIssuer($this->iis);
$data->setAudience($this->aud);
return $this->decode()->validate($data);
}
标签:function,return,uid,JWT,token,使用,configId,public 来源: https://www.cnblogs.com/yanweifeng/p/10943705.html