Skip to content

Instantly share code, notes, and snippets.

@marcoiosif
Last active August 13, 2024 19:16
Show Gist options
  • Save marcoiosif/ac10d8973de1b0981d2be472de75e454 to your computer and use it in GitHub Desktop.
Save marcoiosif/ac10d8973de1b0981d2be472de75e454 to your computer and use it in GitHub Desktop.
Symfony avoid log out after update roles
<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class RefreshRolesSubscriber implements EventSubscriberInterface
{
public function __construct
(
private TokenStorageInterface $tokenStorage
){}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
// don't do anything if it's not the main request
return;
}
$token = $this->tokenStorage->getToken();
if($token instanceof UsernamePasswordToken) $this->refreshRoles($token, $event);
}
private function refreshRoles(UsernamePasswordToken $token, RequestEvent $event):void
{
$user = $token->getUser();
if($user instanceof User && $event->getRequest()->getSession()->get('user_roles') != $user->getRoles())
{
$token = new UsernamePasswordToken($user, $token->getFirewallName(), $user->getRoles());
$this->tokenStorage->setToken($token);
$event->getRequest()->getSession()->set('_security_' . $token->getFirewallName(), serialize($token));
$event->getRequest()->getSession()->set('user_roles', $user->getRoles());
}
}
public static function getSubscribedEvents()
{
return [
'kernel.request' => 'onKernelRequest',
];
}
}
<?php
declare(strict_types=1);
namespace App\Entity;
use Symfony\Component\Security\Core\User\EquatableInterface;
class User implements EquatableInterface
{
public function isEqualTo(UserInterface $user): bool
{
return $this->getUserIdentifier() == $user->getUserIdentifier();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment