Home > Back-end >  Symfony security: Is there an event when a user is authenticated from the session?
Symfony security: Is there an event when a user is authenticated from the session?

Time:06-24

Is there any event when Symfony authenticates a users from the session? LoginSuccessEvent seems only to be fired during an interactive login, e.g. when using a login form but not when a new page is loaded for an already logged in user.

Details:

I am working on a Symfony 6.1 based project and I followed the instructions in the Symfony docs (e.g. here and here) to build security based on a user class and a login form.

Everything works fine: Access to restricted pages is blocked by the firewall, the user is redirected to the login form where he can login. Once logged in, all pages can be accessed until the login expires.

After submitting the login form LoginSuccessEvent is fired. However, when loading a new page using the user from the session, this event is not fired. Is there any other security event for this kind of authentication? None of the events I found in the docs seem to apply to this case.

CodePudding user response:

Indeed, the event is executed only once at login. Alternatively, you can create a kernel.request event that will be fired on every request. In the event, you can pass the Security component to the constructor arguments and get the current user and perform the necessary actions

use App\Entity\User;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Security;

class UserListener
{

    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $user = $this->security->getUser();
        if (!$event->getRequest()->isXmlHttpRequest() and $user instanceof User){
            // do something ...
            dump($user);
        }
    }
}

Registering a listener in services.yaml

App\EventListener\UserListener:
    tags:
        - {name:  kernel.event_listener, event: kernel.request }
  • Related