Home  >  Q&A  >  body text

Refresh token using "PHP-Open-Source-Saver/jwt-auth" library in Laravel 9

I'm making an API in Laravel and I want to create a refresh token routine.

I used the example from the website

<?php

namespace AppHttpControllers;

use IlluminateSupportFacadesAuth;
use AppHttpControllersController;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return IlluminateHttpJsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return IlluminateHttpJsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return IlluminateHttpJsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return IlluminateHttpJsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return IlluminateHttpJsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}

but it shows these errors "Undefined method 'factory'.intelephense(1013)" "Undefined method 'refresh'.intelephense(1013)"

How to execute this refresh token routine? And why this error occurs? In the old version, when the JWT library was still tymondesigns/jwt-auth, this error did not occur.

Laravel 9 PHP 8.1

P粉637866931P粉637866931324 days ago519

reply all(1)I'll reply

  • P粉838563523

    P粉8385635232023-12-24 10:43:32

    You can refresh the token using the following command

    $token = JWTAuth::getToken();
    $new_token = JWTAuth::refresh($token);

    However, if you want the token to refresh on every request (discouraged), add the jwt.refresh middleware in your app\Http\Kernel.php

    protected $routeMiddleware = [
        ...
        'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
        'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
    ];

    reply
    0
  • Cancelreply