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

entity-framework security symfony

Question

I am using the Symfony security setup. Everything works fine, but I don't know how to do one important thing:

In twig, I can reach the current user's info by doing:

Welcome, {{ app.user.username }}

or similar

How do I access this same information in the Controller? Specifically, I want to get the current user entity so I can store it relationally in another entity (one-to-one mapping).

I was really hoping it'd be

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

but that doesn't work. It gives me a class of type

Symfony\Component\Security\Core\User\User

and I want one of type

Acme\AuctionBundle\Entity\User

which is my entity....

1
130
9/20/2012 10:12:15 AM

Accepted Answer

Symfony 4+, 2019+ Approach

In symfony 4 (probably 3.3 also, but only real-tested in 4) you can inject the Security service via auto-wiring in the controller like this:

<?php

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- Approach

As @ktolis says, you first have to configure your /app/config/security.yml.

Then with

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

should be enougth!

$user is your User Object! You don't need to query it again.

Find out the way to set up your providers in security.yml from Sf2 Documentation and try again.

Best luck!

202
4/11/2020 3:35:51 PM

Popular Answer

Best practice

According to the documentation since Symfony 2.1 simply use this shortcut :

$user = $this->getUser();

The above is still working on Symfony 3.2 and is a shortcut for this :

$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 if you want directly the username :

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

If wrong user class type

The user will be an object and the class of that object will depend on your user provider.



Related Questions





Related

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