1.引入php-jwt包
composer require firebase/php-jwt
2.代码
控制器文件:app\api\controller\Jwt.php
3. 自定义封装JWT类文件:
<?php
namespace app\lib;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
use think\Exception;
class JWT
{
/**
* 根据json web token设置的规则生成token
* @return \think\response\Json
*/
public static function createjwt($user_id)
{
//jwt的签发密钥,验证token的时候需要用到
$key = md5(env('dd','pyg'));
//签发时间
$time = time();
//过期时间
$expire = $time + 14400;
$token = array(
"user_id" => "$user_id",
//签发组织
"iss" => env('http//:www.week3.com/','pyg'),
//签发作者
"aud" => env('gqy','pyg'),
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
return JWTUtil::encode($token, $key);
}
/**
* 验证token
* @return \think\response\Json
*/
public static function verifyjwt($jwt)
{
//判断是当前接口是否已经退出
if (in_array($jwt,cache('delete_token')))
{
throw new Exception('token已过期或销毁');
}
//jwt的签发密钥,验证token的时候需要用到
$key = md5('dd', 'pyg');
try {
$jwtAuth = json_encode(JWTUtil::decode($jwt, $key, array("HS256")));
$authInfo = json_decode($jwtAuth, true);
if (!$authInfo['user_id']) {
return json(['code' => 400, 'msg' => '用户不存在', 'data' => '']);
}
//验证成功返回
return json($authInfo);
} catch (ExpiredException $e) {
return json(['code' => 500, 'msg' => 'token已经过期', 'data' => '']);
} catch (\Exception $e) {
return json(['code' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => []]);
}
}
//从请求信息中获取token令牌
public static function getRequestToken()
{
if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
return false;
}
$header = $_SERVER['HTTP_AUTHORIZATION'];
$method = 'bearer';
//去除token中可能存在的bearer标识
return trim(str_ireplace($method, '', $header));
}
}
这篇博客介绍了如何在PHP环境中使用composer引入firebase/php-jwt库,并自定义封装JWT类来创建和验证JSON Web Token(JWT)。内容包括设置密钥、签发和验证token的步骤,以及处理token过期和不存在的情况。
963

被折叠的 条评论
为什么被折叠?



