In Symfony2, how do I retrieve the object that represents the current user?

entity-framework security symfony


I'm using Symfony's security configuration. Everything works OK, but I'm unsure of how to execute one crucial thing:

I can get the current user's information in twig by typing:

Welcome, {{ app.user.username }}

or equivalent

How can I get to the same data in the Controller? I want to get the current user object in particular so that I may save it relationally in another entity (one-to-one mapping).

I truly hoped it would be


nonetheless, it doesn't function. It provides me with a type class.


and I want a kind


which is my organization.

9/20/2012 10:12:15 AM

Accepted Answer

Using Symfony 4+ and 2019+

You can inject the data into symfony 4 (possibly 3.3 as well, but just real-tested in 4).Security service using the controller's auto-wiring as follows:


use Symfony\Component\Security\Core\Security;

class SomeClass
     * @var Security
    private $security;

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

    public function privatePage() : Response
        $user = $this->security->getUser(); // null or UserInterface, if logged in
        // ... do whatever you want with $user

Symfony 2-Based Method

As @ktolis notes, you must first set up your/app/config/security.yml .

After that,

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

should be sufficient!

$user a User Object for you! There is no need to question it once again.

Learn how to configure your providers insecurity.yml to Documentation for Sf2 and try one again.

Good luck!

4/11/2020 3:35:51 PM

Popular Answer

highest standard

Since Symfony 2.1, you may just use the following shortcut:

$user = $this->getUser();

The abbreviation for the following is currently developing Symfony 3.2 as follows:

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

The security.token_storage service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use the getToken() method of the security.context service.

Example: And here is the username if you just want it:

$username = $this->getUser()->getUsername();

the incorrect user class type

The class of the object that the user will be is determined by your customer service.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow