--jwt 是面向離線認證設計的接口權限驗證插件
--是生成token->驗證token的一套流程
/lib/jwt.php
<?php
declare (strict_types = 1);
namespace app\common\lib;
use Exception;
use \Firebase\JWT\JWT;
// 使用jwt加密和解密token
class Auth{
public static function signToken($uid){
$key = md5('my_salt'); //這里是自定義的一個隨機字串,應該寫在config文件中的,解密時也會用,相當 於加密中常用的 鹽 salt
$token=array(
"iss"=>'', //簽發者 可以為空
"aud"=>'', //面象的用戶,可以為空
"iat"=>time(), //簽發時間
"nbf"=>time(), //在什么時候jwt開始生效 (這里表示生成100秒后才生效)
"exp"=> time()+20, //token 過期時間
"data"=>[ //記錄的userid的信息,這里是自已添加上去的,如果有其它信息,可以再添加數組的鍵值對
'uid'=>$uid,
]
);
// print_r($token);
$jwt = JWT::encode($token, $key); //根據參數生成了 token
return $jwt;
}
//驗證token
public static function checkToken($token){
$key = md5('my_salt');
try {
$decoded = json_decode(json_encode(JWT::decode($token, $key, ['HS256'])), true); //HS256方式,這里要和簽發的時候對應
return $decoded;
}catch(Exception $e) { //其他錯誤
return false;
}
}
}
route/app.php
Route::group('/jwt', function () {
Route::rule('/product', 'jwt.jwt/product', 'POST');
Route::rule('/test', 'jwt.jwt/test', 'POST')->middleware(Jwt::class);
});
middleware/jwt.php
<?php
namespace app\admin\middleware;
use Exception;
use app\common\lib\Auth;
use app\common\lib\Redis;
class Jwt
{
public function handle($request, \Closure $next){
// 中間件驗證token
$accessToken = $request->header('access-token');
if(!$accessToken){
throw new Exception('請傳入token');
}
$res = Auth::checkToken($accessToken);
if(!$res){
throw new Exception('jwttoken驗證失敗');
}
var_dump($res);
return $next($request);
}
}