thinkphp6集成JWT
生活随笔
收集整理的這篇文章主要介紹了
thinkphp6集成JWT
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.引入php-jwt包
composer require firebase/php-jwt
2.代碼
控制器文件:app\api\controller\Jwt.php
<?php namespace app\api\controller; use app\BaseController; use Firebase\JWT\ExpiredException; use Firebase\JWT\JWT as JWTUtil; class Jwt extends BaseController {/*** 根據(jù)json web token設(shè)置的規(guī)則生成token* @return \think\response\Json*/public function createjwt(){$key = md5('dd'); //jwt的簽發(fā)密鑰,驗證token的時候需要用到$time = time(); //簽發(fā)時間$expire = $time + 14400; //過期時間$token = array("user_id" => 1,"iss" => "http://www.najingquan.com/",//簽發(fā)組織"aud" => "zz", //簽發(fā)作者"iat" => $time,"nbf" => $time,"exp" => $expire);$jwt = JWTUtil::encode($token,$key);return show(1,"OK",$jwt);}/*** 驗證token* @return \think\response\Json*/public function verifyjwt(){$jwt= input("jwt");$key = md5('dd'); //jwt的簽發(fā)密鑰,驗證token的時候需要用到try{$jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));$authInfo = json_decode($jwtAuth,true);if (!$authInfo['user_id']){return show(0,"用戶不存在");}return show(0,"ok");}catch (ExpiredException $e){return show(0,"token過期");}catch (\Exception $e){return show(0,$e->getMessage());}} }路由:app\api\route\api.php
<?php use think\facade\Route; Route::rule("jwt","jwt/createjwt","get"); Route::rule("verifyjwt","jwt/verifyjwt","post");3.效果如圖所示
圖1.生成token 圖2.token信息總結(jié)
以上是生活随笔為你收集整理的thinkphp6集成JWT的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis实现令牌桶算法思路
- 下一篇: 2021-01-14