Я разработал API, и у меня возникла проблема с истечением срока действия токена, и я пытаюсь найти способы обновления токенов, отправленных через API, использую пользовательское промежуточное программное обеспечение. Когда срок действия токена истек, обновленный токен добавляется взаголовки ответа.Приложению просто нужно выполнить поиск, если ответ есть, и если да, обновить сохраненный токен. Я получаю
{"code": 103, "response": null}
мое промежуточное ПО
<?php
namespace App\Http\Middleware;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class JwtRefresh extends BaseMiddleware {
public function handle($request, Closure $next)
{
try
{
if (! $user = JWTAuth::parseToken()->authenticate() )
{
return response()->json([
'code' => 101, // means auth error in the api,
'response' => null // nothing to show
]);
}
}
catch (TokenExpiredException $e)
{
// If the token is expired, then it will be refreshed and added to the headers
try
{
$refreshed = JWTAuth::refresh(JWTAuth::getToken());
$user = JWTAuth::setToken($refreshed)->toUser();
header('Authorization: Bearer ' . $refreshed);
}
catch (JWTException $e)
{
return response()->json([
'code' => 103, // means not refreshable
'response' => null // nothing to show
]);
}
}
catch (JWTException $e)
{
return response()->json([
'code' => 101, // means auth error in the api,
'response' => null // nothing to show
]);
}
// Login the user instance for global usage
Auth::login($user, false);
return $next($request);
}
}