我已经使用Laravel Passport项目构建了一个RESTful API
它使用客户端凭据授权来授权我的第三方项目
问题是,对于来自第三方应用程序的每个api调用,它会生成一个新的访问令牌
到那天结束时,如果我有999个电话,我将在oauth_access_tokens数据库表中也有999个新记录。
可以避免在数据库中存在大量的访问令牌吗?
也许在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;
}
答案 0 :(得分:3)
<强>解决方案强>
在创建访问令牌时,为Passport生成的事件设置侦听器
应用程序/提供者/ 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();
}
}
应用程序/听众/ 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();
}
}