中间件自定义检测 JWT 并通过自定义异常抛出错误--笔记
很简单,直接贴代码了,更多的作用是写给自己看的
<?php
namespace App\Application\Middleware;
use App\Helpers\ApiException;
use App\Helpers\StatusResponse;
use Closure;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class CheckToken extends BaseMiddleware
{
public function handle($request, Closure $next)
{
try {
//检查请求是否有token
if (!$this->auth->parser()->setRequest($request)->hasToken()){
throw new ApiException('Token not provided', StatusResponse::NOT_AUTH_TOKEN);
}
//检查token是否正确
$guard = Auth::getDefaultDriver(); // 获取当前守护名
$token = Auth::getToken(); // 获取token
$payload = Auth::manager()->getJWTProvider()->decode($token->get()); //解析token
//判断token载荷信息中guard是否与当前guard一致
if(empty($payload['guard']) || $payload['guard'] != $guard){
throw new ApiException('Token Invalid', StatusResponse::TOKEN_INVALID);
}
//检查token是否过期
$this->auth->parseToken()->authenticate();
return $next($request);
}catch (\Exception $exception){
if ($exception instanceof TokenInvalidException){
throw new ApiException($exception->getMessage(), StatusResponse::TOKEN_INVALID);
}
if ($exception instanceof TokenExpiredException){
throw new ApiException($exception->getMessage(), StatusResponse::TOKEN_EXPIRED);
}
}
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接