【发布时间】:2019-07-04 22:18:28
【问题描述】:
我开发了一个API,遇到了token过期的问题,想办法刷新API发送的token,我用的是自定义中间件,token过期时,刷新的token被添加到响应标头。应用程序只需要搜索响应是否有这个,如果有,更新保存的令牌。我得到 p>
{"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);
}
}
【问题讨论】:
-
你刚刚问过这个(至少几乎相同的标题)(stackoverflow.com/questions/54627235/jwt-laravel-token-expired)你为什么不澄清那个问题中的问题而不是再问一次?
-
这又是一个问题
-
那么请使用真正描述问题的标题,而不是通用的“令牌已过期”。令牌过期在这里不是问题,但您无法从响应中检索刷新的令牌这一事实似乎是问题。
-
好的,非常感谢先生 :)
标签: php laravel laravel-5 jwt laravel-5.6