ThinkPHP6 使用JwtToken
1.安装JwtToken
composer require firebase/php-jwt
2.新建PHP类文件
这里新建了Token.php类文件,用于token的签发和验证
<?php
namespace app\home;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class Token
{
protected $salt;
protected $keyId;
public function __construct()
{
$this->salt = md5("1585364631");
}
function getToken($uid): string
{
$currentTime = time();
return JWT::encode([
"iss" => 'dao',
"aud" => '',
"iat" => $currentTime,
"nbf" => $currentTime,
"exp" => $currentTime + 3600 * 24,
"data" => [
'uid' => $uid,
]
], $this->salt, "HS256");
}
public function checkToken($token): array
{
$res = array("code"=>201);
try {
JWT::$leeway = 60;
$decoded = JWT::decode($token, new Key($this->salt, 'HS256'));
return [
"code"=>200,
"data"=>((array)$decoded)['data']
];
} catch(\Firebase\JWT\SignatureInvalidException $e) {
$res['msg']="签名不正确";
}catch(\Firebase\JWT\BeforeValidException|\Firebase\JWT\ExpiredException $e) {
$res['msg']="token失效";
} catch(\Exception $e) {
$res['msg']="token无效";
}
return $res;
}
}
3.新建中间件文件
需要登入使用的进行校验
<?php
namespace app\home\middleware;
use app\home\Token;
use Closure;
use think\Request;
use think\Response;
use think\response\Redirect;
class UserToken
{
/**
* 处理请求
*
* @param Request $request
* @param Closure $next
* @return Response|Redirect
*/
public function handle(Request $request, Closure $next)
{
$token = $request->header('jwtToken',"");
$res = (new Token())->checkToken($token);
if ($res['code'] != 200 ){
return json($res);
}
$request->uid = $res['data']->uid;
return $next($request);
}
}
评论 (0)