PHP code example of gesdinet / jwt-refresh-token-bundle

1. Go to this page and download the library: Download gesdinet/jwt-refresh-token-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gesdinet / jwt-refresh-token-bundle example snippets



return [
    //...
    Gesdinet\JWTRefreshTokenBundle\GesdinetJWTRefreshTokenBundle::class => ['all' => true],
];


namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gesdinet\JWTRefreshTokenBundle\Entity\RefreshToken as BaseRefreshToken;
#[ORM\Entity]
#[ORM\Table(name: 'refresh_tokens')]
class RefreshToken extends BaseRefreshToken
{
}


namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Gesdinet\JWTRefreshTokenBundle\Document\RefreshToken as BaseRefreshToken;
#[ODM\Document(collection: 'refresh_tokens')]
class RefreshToken extends BaseRefreshToken
{
}

public function __construct(
    private readonly ListRefreshTokenManagerInterface $refreshTokens,
    private readonly RefreshTokenManagerInterface $manager,
) {
}

public function sessions(UserInterface $user): array
{
    return array_filter(
        $this->refreshTokens->findAllForUser($user),
        static fn (RefreshTokenInterface $token): bool => $token->isValid()
    );
}

use Gesdinet\JWTRefreshTokenBundle\Model\RevokeRefreshTokenManagerInterface;

public function __construct(
    private RevokeRefreshTokenManagerInterface $refreshTokenManager,
) {
}

public function changeEmail(User $user, string $email): void
{
    // Before the change, while the user still carries the identifier the tokens were issued for
    $this->refreshTokenManager->revokeAllForUser($user);

    $user->setEmail($email);
}


namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gesdinet\JWTRefreshTokenBundle\Entity\RefreshToken;
/**
 * This class extends Gesdinet\JWTRefreshTokenBundle\Entity\RefreshToken to have another table name.
 */
#[ORM\Table('jwt_refresh_token')]
class JwtRefreshToken extends RefreshToken
{
}


namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Gesdinet\JWTRefreshTokenBundle\Document\RefreshToken;
/**
 * This class extends Gesdinet\JWTRefreshTokenBundle\Document\RefreshToken to have another collection name.
 */
#[ODM\Document(collection: 'jwt_refresh_token')]
class JwtRefreshToken extends RefreshToken
{
}


namespace App\Entity;

use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Gesdinet\JWTRefreshTokenBundle\Entity\RefreshTokenRepository;
use Gesdinet\JWTRefreshTokenBundle\Model\AbstractRefreshToken;

#[ORM\Entity(repositoryClass: RefreshTokenRepository::class)]
#[ORM\Table(name: 'refresh_tokens')]
class RefreshToken extends AbstractRefreshToken
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer')]
    #[ORM\GeneratedValue(strategy: 'SEQUENCE')]
    protected int|string|null $id = null;

    #[ORM\Column(name: 'refresh_token', type: 'string', length: 128, unique: true)]
    protected ?string $refreshToken = null;

    #[ORM\Column(type: 'string', length: 255)]
    protected ?string $username = null;

    #[ORM\Column(type: 'datetime')]
    protected ?DateTimeInterface $valid = null;
}

use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;

$data = ['token' => $this->jwtManager->create($user)];
$response = new JsonResponse($data);

$event = new AuthenticationSuccessEvent($data, $user, $response);
$this->eventDispatcher->dispatch($event, Events::AUTHENTICATION_SUCCESS);

// The listener adds the refresh token to the data and the cookie to the response
$response->setData($event->getData());

return $response;

use Gesdinet\JWTRefreshTokenBundle\Generator\RefreshTokenGeneratorInterface;
use Gesdinet\JWTRefreshTokenBundle\Model\RefreshTokenManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

public function __construct(
    private readonly RefreshTokenGeneratorInterface $generator,
    private readonly RefreshTokenManagerInterface $manager,
    #[Autowire('%gesdinet_jwt_refresh_token.ttl%')]
    private readonly int $ttl,
) {
}

public function issueFor(UserInterface $user): string
{
    $refreshToken = $this->generator->createForUserWithTtl($user, $this->ttl);

    $this->manager->save($refreshToken);

    return (string) $refreshToken->getRefreshToken();
}

namespace App\Scheduler;

use Symfony\Component\Console\Messenger\RunCommandMessage;
use Symfony\Component\Scheduler\Attribute\AsSchedule;
use Symfony\Component\Scheduler\RecurringMessage;
use Symfony\Component\Scheduler\Schedule;
use Symfony\Component\Scheduler\ScheduleProviderInterface;
use Symfony\Contracts\Cache\CacheInterface;

#[AsSchedule('default')]
final class MaintenanceSchedule implements ScheduleProviderInterface
{
    public function __construct(private CacheInterface $cache)
    {
    }

    public function getSchedule(): Schedule
    {
        return (new Schedule())
            ->add(RecurringMessage::cron('0 3 * * *', new RunCommandMessage('gesdinet:jwt:clear')))
            // Without this two workers both run it, which is harmless here but rarely is elsewhere
            ->lock($this->cache->getItem('maintenance-schedule'));
    }
}

namespace App\EventListener;

use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\Security\Core\User\UserInterface;

#[AsEventListener('lexik_jwt_authentication.on_authentication_success')]
final class AttachUserToTheResponse
{
    public function __invoke(AuthenticationSuccessEvent $event): void
    {
        $user = $event->getUser();

        if (!$user instanceof UserInterface) {
            return;
        }

        $data = $event->getData();
        $data['user'] = ['nickname' => $user->getNickname()];

        $event->setData($data);
    }
}


namespace App\Request\Extractor;
use Gesdinet\JWTRefreshTokenBundle\Request\Extractor\ExtractorInterface;
use Symfony\Component\HttpFoundation\Request;
final class HeaderExtractor implements ExtractorInterface
{
    public function getRefreshToken(Request $request, string $parameter): ?string
    {
        return $request->headers->get('X-Refresh-Token');
    }
}
bash
# If using the MakerBundle:
php bin/console make:migration
# Without the MakerBundle:
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
bash
php bin/console doctrine:schema:update --dump-sql
php bin/console doctrine:schema:update --force
bash
php bin/console gesdinet:jwt:clear
bash
php bin/console gesdinet:jwt:clear 2015-08-08
bash
php bin/console gesdinet:jwt:clear --batch-size=2500