Php JWT/LARAVEL 5.6刷新过期令牌
我开发了一个API,我遇到了令牌过期的问题,我试图找到刷新API发送的令牌的方法,我使用自定义中间件,当令牌过期时,刷新的令牌被添加到响应头中。应用程序只需要搜索响应是否有此标记,如果有,则更新保存的标记。我得到 {“代码”:103,“响应”:null} 我的中间件Php JWT/LARAVEL 5.6刷新过期令牌,php,laravel,laravel-5,jwt,laravel-5.6,Php,Laravel,Laravel 5,Jwt,Laravel 5.6,我开发了一个API,我遇到了令牌过期的问题,我试图找到刷新API发送的令牌的方法,我使用自定义中间件,当令牌过期时,刷新的令牌被添加到响应头中。应用程序只需要搜索响应是否有此标记,如果有,则更新保存的标记。我得到 {“代码”:103,“响应”:null} 我的中间件 <?php namespace App\Http\Middleware; use Carbon\Carbon; use Closure; use Illuminate\Http\JsonResponse; use Illu
<?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);
}
}
我想你只需要这样做
if ($expired) {
try {
$newToken = $this->auth->setRequest($request)
->parseToken()
->refresh();
$user = $this->auth->authenticate($newToken);
} catch (TokenExpiredException $e) {
return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
} catch (JWTException $e) {
return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
}
// send the refreshed token back to the client
$request->headers->set('Authorization', 'Bearer ' . $newToken);
}
希望这能对您有所帮助。您之前刚问过这个问题(至少是几乎相同的标题)()为什么不澄清该问题中的问题,而不是再次问?这是另一个问题,请使用真正描述问题的标题,而不是通用的“token expired”。令牌过期在这里不是问题,但您无法从响应中检索刷新的令牌似乎是问题所在。好的,非常感谢,先生:)我把这个放在哪里了?在您的捕获中,您正在抛出捕获(令牌过期异常$e)。。。{