首先 composer 安装 firebase/php-jwt
github:https://github.com/firebase/php-jwt
composer require firebase/php-jwt
新建生成token服务层
application\common\service\Token.php
<?php
/**
* Created by PhpStorm.
* User: Pasa吴
* Date: 2019/7/18
* Time: 16:20
*/
namespace app\common\service;
use app\common\exception\ApiException;
use Firebase\JWT\JWT;
/**
* composer require firebase/php-jwt
* github:https://github.com/firebase/php-jwt
*/
class Token
{
private $key = 'pasawuruowohaihuijiandaoniwogairuhezhuheni';
/**
* 签发token
* @param $user_id 用户ID
* @param int $exp_minute token过期时间分钟
* @return string
*/
public function signToken($user_id, $exp_minute = 1)
{
$token = [
"iss" => request()->domain(), //签发者
"aud" => request()->ip(), //面向的用户
"iat" => time(), //签发时间
"nbf" => time() + 3, //在什么时候jwt开始生效
"exp" => time() + 60 * $exp_minute, //token 过期时间
'user_id' => $user_id,
];
$jwt = JWt::encode($token, $this->key);
return $jwt;
}
//验证token
public function checkToken()
{
$token = request()->header('Authorization');
try {
$decoded = JWT::decode($token, $this->key, array('HS256'));
return $decoded;
} catch (\Firebase\JWT\SignatureInvalidException $e) {
throw new ApiException(80001);
} catch (\Firebase\JWT\BeforeValidException $e) {
throw new ApiException(80002);
} catch (\Firebase\JWT\ExpiredException $e) {
throw new ApiException(80003);
} catch (\Exception $e) {
throw new ApiException(80000);
}
}
//获取用户id
public function getUserId(){
$info = $this->checkToken();
return $info->user_id;
}
}
调用方法
use app\common\service\Token;
$token = (new Token)->signToken($user['id'],43200);
本文为Pasa吴原创文章,转载无需和我联系,但请注明来自Pasa吴博客https://www.pasawu.top
最新评论