tp8.0\jwt接口安全验证
·
环境:php8.3\tp8.1\firebase-jwt6.1
app\api\middleware\CheckJwt;
<?php
declare (strict_types = 1);
namespace app\api\middleware;
use app\api\lib\util\JwtUtil;
use Closure;
use think\Request;
use think\Response;
class CheckJwt
{
/**
* 处理请求
*
* @param Request $request
* @param Closure $next
* @return Response
*/
public function handle(Request $request, Closure $next): Response
{
$auth = $request->header('authorization');
if ($auth == null) {
return $next($request);
}
$token = str_replace("Bearer ","",$auth);
$jUtil = new JwtUtil();
$res = $jUtil->verifyJwt($token);
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);
}
}
app\api\lib\util\JwtUtil;
<?php
namespace app\api\lib\util;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class JwtUtil
{
private string $signKey = "quwei";
private int $timeMinutes = 5;
/**
* 根据json web token设置的规则生成token
* @param $userId
* @return string
*/
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.quweiie.cn/",//签发组织
"aud" => "lhd", //签发作者
"iat" => $time, //签发时间
"nbf" => $time, //生效时间
"exp" => $expire //过期时间
);
return JWT::encode($token, $key,'HS256');
}
/**
* 验证token
* @param $token
* @return array
*/
public function verifyJwt($token): array
{
$key = md5($this->signKey); //jwt的签发**,验证token的时候需要用到
try{
$jwtAuth = json_encode(JWT::decode($token, new Key($key, 'HS256')));
$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()];
}
}
}
app\api\controller\auth.php
<?php
namespace app\api\controller;
use app\api\lib\util\JwtUtil;
use think\response\Json;
use think\facade\Db;
class Auth
{
public function login(): Json
{
$username = input('post.username');
$password = input('post.password');
try {
$result = Db::name('users')->where(['username'=>$username, 'password'=>$password])->find();
if (!empty($result)) {
$userId = $result['id'];
$jUtil = new JwtUtil();
$token = $jUtil->createJwt($userId);
} else {
return json(['code'=>500, 'msg'=>'该用户不存在']);
}
} catch (\Exception $e) {
return json(['code'=>500, 'msg'=>$e->getMessage()]);
}
return json(['code'=>200, 'msg'=>'success','token'=>$token]);
}
public function info(): Json
{
if (request()->auth > 0) {
$status = "已登录";
} else {
$status = "未登录";
}
$info = [
'userId'=>request()->auth,
'status'=>$status,
];
return json($info);
}
}
这是完整的步骤,欢迎大家指正。
更多推荐
所有评论(0)