Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current logged User in a service

In Symfony 2.8/3.0, with our fancy new security components, how do I get the currently logged User (i.e. FOSUser) object in a service without injecting the whole container?

Is it even possible in a non-hacky way?

PS: Let's not consider the "pass it to the service function as a parameter" for being trivially obvious. Also, dirty.

like image 702
xDaizu Avatar asked Apr 26 '16 16:04

xDaizu


2 Answers

Inject security.token_storage service into your service, and then use:

$this->token_storage->getToken()->getUser(); 

as described here: http://symfony.com/doc/current/book/security.html#retrieving-the-user-object and here: http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services

like image 150
Miro Avatar answered Sep 19 '22 06:09

Miro


Works with Symfony 3.4, 4.x, 5.x & above. The Security utility class was introduced in Symfony 3.4.

use Symfony\Component\Security\Core\Security;  public function indexAction(Security $security) {     $user = $security->getUser(); } 

https://symfony.com/doc/3.4/security.html#always-check-if-the-user-is-logged-in

like image 42
Kim Avatar answered Sep 22 '22 06:09

Kim