Certainly! What you're describing is commonly known as "sliding sessions" or "sliding expiration." With tymon/jwt-auth, you can achieve this by issuing a new token with each API request (or at least on each authenticated request), thus resetting the TTL (Time To Live).
Here’s how you can implement this:
1. Middleware to Refresh Token
Create a middleware that will check if the user is authenticated and, if so, issue a new token with the updated TTL.
namespace App\Http\Middleware;
use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
class RefreshJwtToken
{
public function handle($request, Closure $next)
{
$response = $next($request);
if (auth()->check()) {
// Generate a new token
$newToken = JWTAuth::fromUser(auth()->user());
// Add the new token to the response headers
$response->headers->set('Authorization', 'Bearer ' . $newToken);
}
return $response;
}
}
2. Register the Middleware
Register your middleware in app/Http/Kernel.php, either globally or for specific routes:
protected $routeMiddleware = [
// ...
'refresh.jwt' => \App\Http\Middleware\RefreshJwtToken::class,
];
3. Apply the Middleware
Apply it to your API routes in routes/api.php:
Route::middleware(['auth:api', 'refresh.jwt'])->group(function () {
// Your protected routes here
});
4. Frontend Handling
On the frontend, make sure to update the stored JWT token with the new one returned in the Authorization header after each API call.
Notes
- This approach will "slide" the session expiration forward with each request.
- Be aware of potential security implications (e.g., token theft).
- You may want to only refresh the token if it's close to expiring, to reduce unnecessary token churn.
Summary:
Yes, you can auto-update the JWT TTL by issuing a new token on each API call using middleware. Just remember to send the new token back to the client and have the client use it for subsequent requests.