DolDurma
DolDurma

Reputation: 17370

Laravel refresh token and getting Unauthorized error

After installing the package "php-open-source-saver/jwt-auth," I need to detect when the user's token has expired, create a new token, and return it to the client.

To implement this, I have written these routes:

Route::prefix('v1')->group(function () {
    Route::group(['middleware' => 'api', 'prefix' => 'auth'], function () {
        Route::controller(AuthController::class)->group(function () {
            Route::post('signup', 'signup');
        })->middleware('throttle:api');

        Route::controller(AuthController::class)
            ->middleware(['json.response', 'jwt.verify', 'jwt.refresh'])
            ->group(function () {
                Route::post('active-account', 'active_account');
            });
    });
});

Here, the route related to signup correctly creates the token and sends it to the client. Its code is as follows:

$user = User::whereUsername($request->username)->first();
$token = auth()->login($user);

Now, after receiving the token, I can easily retrieve user information using the route related to "active-account" and inserting the token in the header part as "Bearer Token" in the first request. But when I send the request again with this route, I receive a "401 Unauthorized" error, although I have placed this array in the routes and middleware sections:

['json.response', 'jwt.verify', 'jwt.refresh']

Now, I expect a new token to be created for the user and sent to the client, but I always receive a "401 Unauthorized" error.

The JwtMiddleware class:

class JwtMiddleware extends BaseMiddleware
{
    public function handle(Request $request, Closure $next): mixed
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (TokenInvalidException $e) {
            return response()->json(['status' => 'Token is Invalid'], 404);
        } catch (TokenExpiredException $e) {
            $current_token  = JWTAuth::getToken();
            $token          = JWTAuth::refresh($current_token);
            return response()->json(
                [
                    'status' => 'Token is Expired',
                    'refresh_token' => $token
                ], 401
            );
        } catch (Exception $e) {
            return response()->json(['status' => 'Authorization Token not found'], 400);
        }
        return $next($request);
    }
}

Definition in Kernel.php file:

protected $middlewareAliases = array(
    ///
    'jwt.verify' => JwtMiddleware::class,
    'jwt.refresh' => RefreshToken::class,
    'json.response' => ForceJsonResponse::class,
    ///
);

Upvotes: 0

Views: 58

Answers (0)

Related Questions