[entity-framework] How do I get the entity that represents the current user in Symfony2?

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

This question is related to entity-framework security symfony

The answer is


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.


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

In symfony >= 3.2, documentation states that:

An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):

use Symfony\Component\Security\Core\User\UserInterface\UserInterface;

public function indexAction(UserInterface $user = null)
{
    // $user is null when not logged-in or anon.
}

This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.

Blog post about it


Well, first you need to request the username of the user from the session in your controller action like this:

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

then do a query to the db and get your object with regular dql like

$em = $this->get('doctrine.orm.entity_manager');    
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();

the $user should now hold the user with this username ( you could also use other fields of course)

...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:

security:
 provider:
  example:
   entity: {class Acme\AuctionBundle\Entity\User, property: username}

hope this helps!


The thread is a bit old but i think this could probably save someone's time ...

I ran into the same problem as the original question, that the type is showed as Symfony\Component\Security\Core\User\User

It eventually turned out that i was logged in using an in memory user

my security.yml looks something like this

security:
    providers:
        chain_provider:
            chain:
                providers: [in_memory, fos_userbundle]
        fos_userbundle:
            id: fos_user.user_manager
        in_memory:
            memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN', 'ROLE_SONATA_ADMIN' ] }

the in_memory user type is always Symfony\Component\Security\Core\User\User if you want to use your own entity, log in using that provider's user.

Thanks, hj


Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to symfony

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2 The CSRF token is invalid. Please try to resubmit the form What is the difference between .yaml and .yml extension? How can I use break or continue within for loop in Twig template? Running Composer returns: "Could not open input file: composer.phar" Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings Symfony - generate url with parameter in controller Call PHP function from Twig template