Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony getting logged in user's id

I am developing an application using Symfony2 and doctrine 2. I would like to know how can I get the currently logged in user's Id.

like image 899
Haritz Avatar asked May 10 '12 15:05

Haritz


People also ask

How to get current user id in Symfony?

Since Symfony 2.6 you can retrieve a user from the security token storage: $user = $this->get('security. token_storage')->getToken()->getUser();

How to logout user Symfony?

Logout in Symfony2 is handled by so called logout handler which is just a lister that is executed when URL match pattern from security configuration, ie. if URL is let's say /logout then this listener is executed. There are two build-in logout handlers: CookieClearingLogoutHandler which simply clears all cookies.


1 Answers

Current Symfony versions (Symfony 4, Symfony >=3.2)

Since Symfony >=3.2 you can simply expect a UserInterface implementation to be injected to your controller action directly. You can then call getId() to retrieve user's identifier:

class DefaultController extends Controller {     // when the user is mandatory (e.g. behind a firewall)     public function fooAction(UserInterface $user)     {         $userId = $user->getId();      }      // when the user is optional (e.g. can be anonymous)     public function barAction(UserInterface $user = null)      {         $userId = null !== $user ? $user->getId() : null;     } } 

You can still use the security token storage as in all Symfony versions since 2.6. For example, in your controller:

$user = $this->get('security.token_storage')->getToken()->getUser(); 

Note that the Controller::getUser() shortcut mentioned in the next part of this answer is no longer encouraged.

Legacy Symfony versions

The easiest way to access the user used to be to extend the base controller, and use the shortcut getUser() method:

$user = $this->getUser(); 

Since Symfony 2.6 you can retrieve a user from the security token storage:

$user = $this->get('security.token_storage')->getToken()->getUser(); 

Before Symfony 2.6, the token was accessible from the security context service instead:

$user = $this->get('security.context')->getToken()->getUser(); 

Note that the security context service is deprecated in Symfony 2 and was removed in Symfony 3.0.

like image 196
Jakub Zalas Avatar answered Sep 17 '22 13:09

Jakub Zalas