中介軟體自定義檢測 JWT 並通過自定義異常丟擲錯誤--筆記

Colorado發表於2020-06-15

很簡單,直接貼程式碼了,更多的作用是寫給自己看的

<?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 協議》,轉載必須註明作者和本文連結

相關文章