1.camposer 安装JWT类
composer require firebase/php-jwt
2.在App文件下新建Server文件夹,新建JwtServer类
?3.类中写入以下代码
<?php
namespace App\Server;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use phpDocumentor\Reflection\Types\False_;
class JwtServer
{
public static function createToken($userId)
{
$key = "example_key";
$payload = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
"nbf" => 1357000000,
'user_id'=>$userId
);
$jwt = JWT::encode($payload, $key, 'HS256');
return $jwt;
}
public static function decodeToken($jwt){
$key = "example_key";
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
if ($decoded){
return $decoded;
}else{
return false;
}
}
}
4.新建中间件
php artisan make:middleware CheckApiLogin
5.在中间件中写入 ,将token放入header中传输
public function handle(Request $request, Closure $next)
{
//将token放入header中传输
$token=$request->header('token');
if (!$token){
return response()->json(['code'=>500,'msg'=>'token不存在','data'=>[]]);
}
$userId=JwtServer::decodeToken($token);
if ($userId){
//将加密id解密传入下一步
$request->attributes->add(['user_id'=>$userId]);
}else{
return response()->json(['code'=>500,'msg'=>'token过期','data'=>[]]);
}
return $next($request);
}
6.注册中间件
'checkApiLogin' => \App\Http\Middleware\CheckApiLogin::class
7.在路由中使用中间件
Route::group(['middleware'=>'checkApiLogin'],function (){
});
?
8.获取token解密的凭证这里使用的是userId
public function index(Request $request)
{
$userId=$request->get('user_id');
}
|