Sanctum expired tokens not removed from personal_access_token table when expired, how to remove them?
Sanctum is a popular authentication package for Laravel applications. It provides various ways to generate and manage access tokens, including personal access tokens (PATs). PATs are long-lived tokens intended for use by individual developers or API clients.
By default, Sanctum sets the token expiration time to never for PATs. However, you may want to set an expiration time for security reasons or to manage token usage. When a token expires, it should no longer be valid and should be removed from the database to prevent unauthorized access.
If you have Sanctum tokens that have expired but are still present in the personal_access_tokens
table, you can remove them using Laravel's database query builder or Eloquent ORM.
First, let's check the current tokens in the personal_access_tokens
table using Laravel's Tinker console:
php artisan tinker
// Get all personal access tokens
$tokens = DB::table('personal_access_tokens')->get();
// Display the tokens
$tokens->each(function ($token) {
echo $token->token;
echo ' (' . $token->expires_at->format('Y-m-d H:i:s') . ')' . PHP_EOL;
});
Next, let's remove the expired tokens using Laravel's query builder:
// Remove expired tokens
DB::table('personal_access_tokens')->where('expires_at', '<', now())->delete();
Or, using Eloquent ORM:
// Remove expired tokens using Eloquent
$tokens = DB::table('personal_access_tokens as pat')->where('pat.expires_at', '<', now())->delete();
Both queries will remove the expired tokens from the personal_access_tokens
table.
If you want to schedule this task to run periodically, you can create a Laravel Artisan command or use Laravel's scheduler to run the query at regular intervals. For example, you can add the following code to your App\Console\Kernel.php
file to schedule the token cleanup task every day at midnight:
protected function schedule(Schedule $schedule)
{
$schedule->command('token:cleanup')->daily();
}
And then create a new Artisan command file App\Console\Commands\TokenCleanup.php
:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class TokenCleanup extends Command
{
protected $signature = 'token:cleanup';
protected $description = 'Clean up expired personal access tokens';
public function handle()
{
DB::table('personal_access_tokens')->where('expires_at', '<', now())->delete();
$this->info('Expired personal access tokens have been removed.');
}
}
Now, you can run the token:cleanup
command manually or schedule it to run automatically using Laravel's scheduler.
By following these steps, you can remove expired tokens from the personal_access_tokens
table and maintain the security of your Laravel application.