第一步:
引入 php-jwt 包
composer require firebase/php-jwt
第二步:
控制器文件代码:app\controller\JWT.php
<?php
namespace app\busines;
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('TOKEN.key'));
//签发时间
$time = time();
//过期时间
$expire = $time + 14400;
$token = array(
"user_id" => "$user_id",
//签发组织
"iss" => env('TOKEN.iss'),
//签发作者
"aud" => env('TOKEN.aud'),
"iat" => $time,
"nbf" => $time,
"exp" => $expire
);
return json(JWTUtil::encode($token, $key));
}
/**
* 验证token
* @return \think\response\Json
*/
public static function verifyjwt($jwt)
{
//查看token是否过期(在退出登录的逻辑里会手动让其过期)
if (!empty(cache('delete_token')) && in_array($jwt, cache("delete_token"))) {
throw new ExpiredException("token过期","400");
}
//jwt的签发密钥,验证token的时候需要用到
$key = md5(env('TOKEN.key'));
try {
$jwtAuth = json_encode(JWTUtil::decode($jwt, $key, array("HS256")));
$authInfo = json_decode($jwtAuth, true);
if (!$authInfo['user_id']) {
throw new Exception('用户ID不存在','500');
}
//验签成功返回
return json($authInfo);
} catch (ExpiredException $e) {
throw new Exception('token过期','500');
} catch (\Exception $e) {
throw new Exception($e->getMessage(),'500');
}
}
//从请求信息中获取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));
}
}
第三步:
获取到请求头的 Authorization
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/?s=$1 [QSA,PT,L]
#增加下面这项
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
</IfModule>
第四步:
进行书写路由
<?php
use think\facade\Route;
Route::rule("jwt","jwt/createjwt","get");
Route::rule("verifyjwt","jwt/verifyjwt","post");
第五步:
生成 token
$token = JWT::createjwt( $user_id );
第六步:
验证是否成功
//取出token
$token=JWT::getRequestToken();
try {
//校验token
$data=JWT::verifyjwt($token);
}catch (\Exception $exception){
return json([
'code'=>600,
'msg'=>$exception->getMessage(),
'data'=>'',
]);
}