0

My concern is creating refresh token API and executing that endpoint on each and every request. Isn't that extra request for application. Is this the right way to do ?

Is there any better solution for bearer token expiry for Single page application.

1 Answers1

0

Laravel sanctum from version 3 has expire_at column. while creating token you can pass third arg as expire time.

$user->createToken('device_name', ['*'], Carbon::now()->addHours(2))->plainTextToken;

After that create middleware in laravel in order to updated expire_at column

public function handle(Request $request, Closure $next): Response
{
    $user = $request->user();
    
    if( $user ):            
        $token = $user->currentAccessToken();
        $token->forceFill([
            'expires_at' => Carbon::now()->addHours(2)
        ])->save();
    endif;

    return $next($request);
}

Add your middleware in Kernal.php $middlewareGroups api section.

In above example token will expiry after two hours of user last activity.