How To Clear All The Expired Tokens From The Database With Fosoauthserverbundle

As you should know, everytime a request to the /oauth route of your application is executed (with FOSOAuthServerBundle implemented), you'll register a token in your database in the access_token table (or according to the grant_type parameter of your request in auth_code table).

A developer in their right mind, would not want to have useless records in the database, therefore we need to clean the database from expired oauth tokens. There are 2 ways to clean the tokens from your database : executing the clean command of the bundle or copy the same logic and execute it from a controller (or a service) directly. 

FOSOAuthServer bundle has already an implemented clean command that will do the trick for you. Just execute the following command from the command line :

$ php app/console fos:oauth-server:clean

You'll get an output similar to :

You can also clear all the expired tokens from a symfony controller of the same way that the command does. Retrieve a service, and access the deleteExpired function like this:

<?phpnamespace myappmyBundleController;use SymfonyBundleFrameworkBundleControllerController;class AdminController extends Controller{    public function cleartokensAction(){       $services = array( 'fos_oauth_server.access_token_manager' => 'Access token', 'fos_oauth_server.refresh_token_manager' => 'Refresh token', 'fos_oauth_server.auth_code_manager' => 'Auth code', );        $info = array(); foreach ($services as $service => $name) { /** @var $instance TokenManagerInterface */ // if you're not from a controller, you need to inject the container and the use the get option $instance = $this->get($service); if ($instance instanceof TokenManagerInterface || $instance instanceof AuthCodeManagerInterface) { $result = $instance->deleteExpired();               array_push($info,array(                  'serviceName' => $name,                  'numberDeletedTokens' => $result                )); } }        var_dump($info); // dump an array with the same structure as the shown in the first image. // handle the response by yourself, otherwise this will throw error.    }}

Of course you need to protect this function from be inaccessible for users without the proper rights (no admin).

If you want to automate this task, you can create a crontab in your OS to execute the command (or a php file with the code providen in the controller) when you want. Have fun !

  • 234