DEV Community

Nacho Colomina Torregrosa
Nacho Colomina Torregrosa

Posted on • Updated on

Accessing Symfony security user on the background

In this short post I would like to show how to access symfony logged user in the background. When we want to access user on a Symfony controller, we can do it easily following this way:

   class MyController extends AbstractController
   {
      #[Route('/my-route', name: 'my_route')]
      public function myAction(): Response
      {
          $user = $this->getUser();
      }
   }
Enter fullscreen mode Exit fullscreen mode

This is valid only in real-time where you have access to the request, but you cannot do it, for instance, in a message handler since it runs in the background where there is no access to the request.

So, what we can do to access user in the background?. The solution is to pass the user identifier so it can be accessed in the background and we can load the user. Let's see it with an example using symfony messenger:

   class MyMessage
   {
      public function __construct(
         public readonly string $userIdentifier
      ){ }
   }
Enter fullscreen mode Exit fullscreen mode
   class MyController extends AbstractController
   {
      #[Route('/my-route', name: 'my_route')]
      public function myAction(): Response
      {
          $this->bus->dispatch(new MyMessage($this->getUser()->getUserIdentifier()));
      }
   }
Enter fullscreen mode Exit fullscreen mode

As we can see in the above code block, we've created a message model which accepts user identifier as an argument. The second block dispatches a message to the background passing as an argument the logged user identifier.

Now, we can access it in the message handler and load the user in the way we want like retreiving it from the database, as we can see in the following code block:

   #[AsMessageHandler]
   class MyMessageHandler
   {
      public function __construct(
         private readonly EntityManagerInterface $em
      ){ }

      public function __invoke(MyMessage $message): void
      {
         $this->em->getRepository(User::class)->find($message->userIdentifier);
      }
  }
Enter fullscreen mode Exit fullscreen mode

I've recently published an ebook where i show how to build an operation-oriented api using PHP and Symfony. This book uses a similar way to give to an operation access to the authenticated user. If you want to read it, you can find it here.

Top comments (0)