Ryan H
Ryan H

Reputation: 2945

Laravel JWT auth get User ID when refreshing token

I'm using the tymon jwt-auth package and am utilising refresh tokens. My database has a column for when a user last logged in, which is set upon log in to my app, but I need to update this column when the user's token is refreshed.

I'm having some trouble getting the id of the user, so that I know to update their record, Auth::id() is null, and thus never runs.

Even if I run this after doing a refresh. How can I obtain the user to update their last logged in column?

/**
 * Refresh a token.
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function refresh()
{
    try {
        if (Auth::id()) {
            ProcessLastUserLogin::dispatch(
                Auth::id(), Carbon::now()
            );
        } else {
            Log::debug('unable to obtain user ID');
        }
    } catch (\Exception $e) { }

    // return refresh token
    return $this->respondWithToken(auth()->refresh(), true);
}

UPDATE

I've tried the following:

public function refresh()
{
    $user = JWTAuth::parseToken()->authenticate();
    Log::debug('user', [
        'user' => $user
    ]);
    return $this->respondWithToken(auth()->refresh());
}

No user is logged upon token refresh, error thrown:

[2021-10-15 14:41:11] local.ERROR: Token has expired {"exception":"[object] (Tymon\JWTAuth\Exceptions\TokenExpiredException(code: 0): Token has expired at /Users/ryanholton/Sites/project-beacon-api/vendor/tymon/jwt-auth/src/Claims/Expiration.php:31) [stacktrace]

Upvotes: 1

Views: 845

Answers (1)

Bozlur Rahman
Bozlur Rahman

Reputation: 547

I have also faced with same problem like you. Most probably you are importing JWTAuth class from use Tymon\JWTAuth\JWTAuth. If i am right, then you just need to use use Tymon\JWTAuth\Facades\JWTAuth; Hope it will resolve your problem.

Upvotes: 0

Related Questions