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
;
}
}

 

输出:

image

 

 


posted @ 2017-05-31 19:51  徐锅  阅读(197)  评论(0编辑  收藏  举报