1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
namespace App\Http\Middleware;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class RefreshToken extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$newToken = null;
$this->auth->unsetToken();
$this->checkForToken($request);
try {
$user = $this->auth->parseToken()->authenticate();
if (!$user) {
return response()->json([
'status_code' => 401,
'message' => '未查询到该用户信息',
'time' => time(),
], 401);
}
var_dump($user); // 后面几次user都是有信息的
} catch (TokenExpiredException $e) {
try {
$newToken = $this->auth->refresh();
$request->headers->set('Authorization', 'Bearer ' . $newToken);
} catch (JWTException $e) {
// 过期用户
return response()->json([
'status_code' => 401,
'message' => '账号信息过期了,请重新登录',
'error' => $e->getMessage(),
'time' => time(),
], 401);
}
} catch (JWTException $e) {
var_dump('JWTException 65');
return response()->json([
'status_code' => 401,
'message' => '登录信息已过期,请重新登录.',
'error' => $e->getMessage(),
'time' => time(),
], 401);
}
$respOnse= $next($request);
if ($newToken) {
$response->headers->set('Authorization', 'Bearer ' . $newToken);
}
return $response;
}
}
|