1.通过 composer 下载插件
composer require firebase/php-jwt
2.
<?php
namespace app\business;
use Firebase\JWT\Key;
use think\Exception;
class Jwt
{
public static function createJwt($userId = 'zq')
{
$key = md5('zq8876!@!'); //jwt的签发密钥,验证token的时候需要用到
$time = time(); //签发时间
$expire = $time + 14400; //过期时间
$token = array(
"user_id" => $userId,
"iss" => "http://www.najingquan.com/",//签发组织
"aud" => "zhangqi", //签发作者
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
// 生成token
$jwt = \Firebase\JWT\JWT::encode($token, $key,'HS256');
return $jwt;
}
public static function verifyJwt($jwt = '')
{
$key = md5('zq8876!@!');
try {
$jwtAuth = json_encode(\Firebase\JWT\JWT::decode($jwt, new Key($key,'HS256')));
$authInfo = json_decode($jwtAuth, true);
$msg = [];
if (!empty($authInfo['user_id'])) {
$msg = [
'status' => 1001,
'msg' => 'Token验证通过'
];
return $authInfo['user_id'];
} else {
throw new Exception("用户不存在");
}
} catch (\Firebase\JWT\ExpiredException $e) {
throw new Exception("token过期");
} catch (\Exception $e) {
throw new Exception("token无效");
}
}
}
3.定义中间件
php think make:middleware Check
<?php
declare (strict_types = 1);
namespace app\middleware;
use app\business\Jwt;
use think\db\exception\DbEventException;
use think\Exception;
class CheckToken
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
// 取出token
$token=$_SERVER["HTTP_TOKEN"];
// 验证token
try {
$user_id=Jwt::verifyJwt($token);
$request->user_id=$user_id;
}catch (Exception $exception){
return fail("token异常");
}
return $next($request);
}
}
4..登录成功颁发token
$token=Jwt::createJwt($id);
5.引用中间件
Route::get('list','Hotels/list')->middleware(\app\middleware\CheckToken::class);
6.小程序登录前端获取token并缓存
success({data:{data}}){
console.log(data)
wx.setStorage({
key:"token",
data:data
})
7.小程序其他需登录页面才可查看时 每次访问需携带token
onLoad: function (options) {
let that = this
let token = wx.getStorageSync('token');
wx.request({
url: 'http://www.www.com/index.php/list',
data:{
pagesize:10
},
header:{
token:token
},
success(e){
that.setData({
data:e.data.data.data,
last_page:e.data.data.last_page
})
}
})
},