智威汤逊/ LARAVEL 5.6刷新令牌过期

问题描述 投票:0回答:1

我开发了一个API,我有与令牌到期的问题,我想方设法刷新由API发出的令牌,我使用自定义的中间件,当令牌已过期,刷新令牌添加到响应头。该应用程序只需要搜索,如果响应有这个,如果是这样,更新保存token.I得到

{ “代码”:103, “响应”:空}

我中间件

<?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);
    }
}
php laravel laravel-5 jwt laravel-5.6
1个回答
1
投票

我想你只需要做到这一点,

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);
}

希望这将帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.