首页 > 代码库 > jwt实现
jwt实现
<?php
namespace app\admin\controller;
use think\Config;
use think\Controller;
use think\Request;
use think\cache\driver\Redis;
/**
* Class Base
* @package app\admin\controller
*/
class Base extends Controller
{
/**
* Base constructor.
* @param Request|null $request
*/
public function __construct(Request $request = null)
{
not_region(true);//允许
parent::__construct($request);
}
static function getAdminKey()
{
$admin_key = Config::get(‘key‘)["admin_key"];
return $admin_key;
}
/**
* @var
*/
protected $head;
/**
* @var
*/
protected $payload;
/**
* @param string $iss 发行者
* @param string $exp 过期时间
* @param $uid int 用户id
* @return array
*/
protected function payload($uid)
{
$this->payload = [
‘iss‘=>request()->domain(),
‘exp‘=>time(),
‘uid‘=>$uid,
];
return $this->payload;
}
protected function head()
{
$this->head = [
‘type‘=>"JWT",
‘alg‘=>‘HA256‘,
];
return $this->head ;
}
/**
* @param $str
* @return string
*/
static function baseEn($str)
{
return base64_encode($str);
}
/**
* @param $str
* @return string
*/
static function baseDe($str)
{
return base64_decode($str);
}
/**
* @param $strdata
* @return string
*/
static function hash_hmac($strdata)
{
$hashSha256 = self::baseEn(hash_hmac("sha256",$strdata,"secret",true));
return $hashSha256;
}
/**
* @param array $head $this->head();/other
* @param array $payload $this->payload();/other
* @return string
*/
static function base64_meger($head=[],$payload=[],$redis)
{
$new_arr = [];
foreach (func_get_args() as $keies)
{
if(is_array($keies)){
$new_arr[] = self::baseEn(json_encode($keies));
}
}
$new_signature = implode(‘.‘,$new_arr);
// ----------- 签名生成------
$signature = self::hash_hmac($new_signature);
// ------------保存签名------
self::setRedis($redis,$signature);
$token = $new_signature.‘.‘.$signature;
return $token;
}
/**
*
* @param Redis $redis
* @param $signature
* @return bool
*/
protected static function setRedis($redis,$signature)
{
return $redis->set(self::getAdminKey(),$signature);
}
}
实现:
<?php
namespace app\admin\controller;
use think\cache\driver\Redis;
/**
* Class Index
* @package app\admin\controller
*/
class Index extends Base
{
public function index(Redis $redis)
{
$token = $this::base64_meger($this->head(),$this->payload(2),$redis);
return $token;
}
}
输出:
jwt实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。