Learn how to clean the expired tokens from your database generated by FOSOAuthServer bundle in your symfony project.

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. 

Command

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 :

FOSOauthServerBundle

Controller

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:

<?php

namespace myapp\myBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

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 !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors