Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

degeta10's avatar

Passport, Method to refresh token after expiring

I'm using laravel v5.8, VueJS and passport v7.4 for Authentication. Below is my login function:

public function login(Request $request)
{
    $validator = Validator::make($request->all(), [
        'email' => 'required|string|email',
        'password' => 'required|string',
    ]);

    if ($validator->fails()) {
        return response([
            'status' => 0,
            'message' => $validator->errors()->first()
        ]);
    }

    $credentials = request(['email', 'password']);

    if (!Auth::attempt($credentials))
        return response()->json([
            'status' => 0,
            'message' => 'Unauthorized'
        ], 401);


    $user = $request->user();

    $tokenResult = $user->createToken('authToken');
    $token = $tokenResult->token;
    $token->save();

    $user_role = Auth::user()->user_type;
    $user->assignRole($user_role);

    return response()->json([
        'status' => 1,
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
        'expires_at' => Carbon::parse(
            $tokenResult->token->expires_at
        )->toDateTimeString(),
    ]);
}

My issue is my token expires in 10 seconds(this is for testing purpose). So I check for every route if the token is expired using the below function in VueJS:

isValid(token) {
        const payload = this.payload(token);
        if (payload) {
            const datetime = Math.floor(Date.now() / 1000);
            return payload.exp >= datetime ? true : false;
        }
        return false;
}

So this works fine, but what should i do to refresh the token? Can we make a middleware to handle it by itself? Or Is there anyway to detect if the user is actively using the application like in normal session based authentication?

0 likes
0 replies

Please or to participate in this conversation.