uni-app/thinkphp:用jwt实现登录之一:服务端php(thinkphp v6.0.12LTS)
一,安装firebase/php-jwt扩展:
1,命令:
liuhongdi@lhdpc:/data/php/admapi$ composer require firebase/php-jwt
2,安装成功后的位置:
3,查看firebase/php-jwt的版本:
liuhongdi@lhdpc:/data/php/admapi$ composer show firebase/php-jwt
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/05/uniapp-thinkphp-yong-jwt-shi-xian-deng-lu-zhi-yi-fu-wu-duan/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,php的代码
1,app\middleware\CheckJwt.php
<?php declare (strict_types = 1); namespace app\middleware; use app\lib\util\JwtUtil; class CheckJwt { /** * 处理请求 * * @param \think\Request $request * @param \Closure $next * @return Response */ public function handle($request, \Closure $next) { $auth = $request->header('authorization'); if ($auth == null) { return $next($request); } $token = str_replace("Bearer ","",$auth); $jUtil = new JwtUtil(); $res = $jUtil->verifyjwt($token); //var_dump($res); if (isset($res['code']) && isset($res['userId']) && $res['code'] == 0 && is_int($res['userId'])) { $userId = $res['userId']; $request->auth = $userId; } else { $request->auth = 0; } return $next($request); } }
2,controller/Auth.php
<?php declare (strict_types = 1); namespace app\controller; use app\BaseController; use think\facade\Cache; use think\Request; use app\result\Result; use think\response\Json; use app\validate\Login as LoginValidate; use think\exception\ValidateException; use app\lib\util\JwtUtil; class Auth extends BaseController { /** * 登录 * * @return \think\Response */ public function login():Json { try { validate(LoginValidate::class) ->check($_POST); } catch (ValidateException $e) { // 验证失败 输出错误信息 return Result::Error(422,$e->getError()); } if ($_POST["mobile"] == "13811668588" && $_POST["password"] == "111111"){ //验证成功,生成jwt返回 $userId = 123; $jUtil = new JwtUtil(); $token = $jUtil->createJwt($userId); $res = ["token"=>$token]; return Result::Success($res); } else { return Result::Error(422,"用户名密码错误"); } } /** * 得到用户信息 * * @return \think\Response */ public function info() { if ($this->request->auth > 0) { $status = "已登录"; } else { $status = "未登录"; } $info = [ 'userId'=>$this->request->auth, 'status'=>$status, ]; return Result::Success($info); } }
3,lib/util/JwtUtil.php
<?php namespace app\lib\util; use Firebase\JWT\ExpiredException; use Firebase\JWT\JWT; use Firebase\JWT\Key; class JwtUtil { private $signKey = "lhd@2001:liuhongdi"; private $timeMinutes = 5; private $alg = "HS256"; /** * 根据json web token设置的规则生成token * @return \think\response\Json */ public function createJwt($userId):string { $key = md5($this->signKey); //jwt的签发**,验证token的时候需要用到 $time = time(); //签发时间 $expire = $time + $this->timeMinutes*60; //过期时间 $token = array( "userId" => $userId, "iss" => "http://www.liuhongdi.com/",//签发组织 "aud" => "lhd", //签发作者 "iat" => $time, //签发时间 "nbf" => $time, //生效时间 "exp" => $expire //过期时间 ); $jwt = JWT::encode($token,$key,$this->alg); return $jwt; } /** * 验证token * @return \think\response\Json */ public function verifyjwt($token) { $key = md5($this->signKey); //jwt的签发**,验证token的时候需要用到 try{ $jwtAuth = json_encode(JWT::decode($token,new Key($key, $this->alg))); $authInfo = json_decode($jwtAuth,true); if (!$authInfo['userId']){ return ['code'=>0,'msg'=>"用户不存在"]; } return ['code'=>0,'userId'=>$authInfo['userId'],'msg'=>"ok"]; }catch (ExpiredException $e){ return ['code'=>0,'msg'=>"token过期"]; }catch (\Exception $e){ return ['code'=>0,'msg'=>$e->getMessage()]; } } }
4,route/app.php 路由中需要配置上checkjwt,用来得到token中的用户信息
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- use think\facade\Route; Route::group('auth', function () { Route::post('login', 'auth/login'); Route::get('info', 'auth/info')->middleware(\app\middleware\CheckJwt::class);; }); Route::group('item', function () { Route::get('one', 'item/one'); Route::get('list', 'item/list'); });
三,查看thinkphp的版本:
[lhdop@blog tpapibase]$ /usr/local/soft/php7/bin/php think version v6.0.12LTS