travel/service/app/middleware/auth.php

53 lines
1.5 KiB
PHP

<?php
namespace app\middleware;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\Key;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class auth implements MiddlewareInterface
{
public function process(Request $request, callable $next): Response
{
$path = $request->path();
if($path) {
//白名单
$url = [
'/user/index/login',
'/user/index/forget',
'/user/index/register',
];
if(in_array($path, $url)) {
return $next($request);
}
}
$token = $request->header('Authorization');
if(empty($token)) {
$token = $request->cookie('token');
}
if(empty($token)) {
return response(json_encode(['code' => 403, 'msg'=> 'token expire']));
}
try {
$key = new Key(config('app.jwt_key'), 'HS256'); // 密钥
$decoded = JWT::decode(str_replace('Bearer ','',$token), $key);
if($decoded->data) {
$request->user = $decoded->data;
}
}catch (ExpiredException $e){
return response(json_encode(['code' => 403, 'msg'=> 'token expired']));
}catch (\Exception $e){
return response(json_encode(['code' => 403, 'msg'=> 'token expire']));
}
$response = $next($request);
return $response;
}
}