一 : 下载第三方插件
composer require lcobucci/jwt 3.3
二 : 创建相关的控制器
1:生成&校验token的控制器
php artisan make:controller Api/TokenController
2:登录的控制器
php artisan make:controller Api/LoginController
3:创建中间件
php artisan make:middleware TokenMiddleWare
三 : 在新建的token控制器内命名空间下调用
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;
四 : 生成token的方法
//生成token
static public function createToken($uid=null){
$signer = new Sha256();//加密规则
$time = time();//当前时间
$token = (new Builder())
->issuedBy('teacher')//签发人
->canOnlyBeUsedBy('student')//接收人
->identifiedBy('kaslana', true) //标题id
->issuedAt($time)//发出令牌的时间
->canOnlyBeUsedAfter($time) //生效时间(即时生效)
->expiresAt($time + 3600) //过期时间
->with('uid', $uid) //用户id
->sign($signer, 'kiana') //签名
->getToken(); //得到token
return (string)$token;
}
五 : 校验token的方法
//验证token
static public function verifyToken($token=null){
//检测是否接收到了token
if(empty($token)){
return 0;
}
//代码到30行,就表示取到token了,那么转化成jwt认识的token
$token = (new Parser())->parse((string) $token);
//验证基本设置
$data = new ValidationData