是否可以避免数据库中出现大量访问令牌?

Is it possible to avoid huge number of access tokens in database?

我用 Laravel Passport 项目构建了 RESTful API。
它正在使用 Client Credentials Grant 来授权我的第三方项目。
问题是,对于来自第三方应用程序的每个 api 调用,它都会生成一个新的访问令牌。
到一天结束时,如果我有 999 个电话,我也会在 oauth_access_tokens 数据库中有 999 个新记录 table。
是否可以避免数据库中的大量访问令牌?

也许在 League\OAuth2\Server\Grant\ClientCredentialsGrant.php:

public function respondToAccessTokenRequest(ServerRequestInterface $request, ResponseTypeInterface $responseType, \DateInterval $accessTokenTTL) {
    $client = $this->validateClient($request);
    $scopes = $this->validateScopes($this->getRequestParameter('scope', $request));
    $scopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client);
    // $validToken = query to check if $client has existing token neither revoked or expired
    // if ($validToken) { 
    //     return $responseType->setAccessToken($validToken);
    // }
    $accessToken = $this->issueAccessToken($accessTokenTTL, $client, null, $scopes);
    $responseType->setAccessToken($accessToken);
    return $responseType;
}

解决方案
为创建访问令牌时 Passport 生成的事件设置侦听器。

app/Providers/eventServiceProvider.php:

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {
    protected $listen = [
        'Laravel\Passport\Events\AccessTokenCreated' => [
            'App\Listeners\RevokeOldTokens'
        ]
    ];
    public function boot() {
        parent::boot();
    }
}

app/Listeners/RevokeOldTokens.php:

<?php

namespace App\Listeners;

use Laravel\Passport\Events\AccessTokenCreated;
use Laravel\Passport\Client;
use Carbon\Carbon;

class RevokeOldTokens {
    public function __construct() {
        //
    }
    public function handle(AccessTokenCreated $event) {
        $client = Client::find($event->clientId);
        // delete this client tokens created before one day ago:
        $client->tokens()->where('created_at', '<', Carbon::now()->subDay())->forceDelete();
    }
}