简体   繁体   中英

How do I get the logged in user's id in symfony 4?

The user can log in, but i need his id to show his profile. Since i'm working in symfony 4, the many possible answers i've found were obsolete.

https://symfony.com/doc/current/security.html#retrieving-the-user-object

After authentication, the User object of the current user can be accessed via the getUser() shortcut (which uses the security.token_storage service). From inside a controller, this will look like:

public function index()
{
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

    $user = $this->getUser();
}

The user will be an object and the class of that object will depend on your user provider. But, you didn't tell us what user provider you are using, so I have no way of telling you, beyond this, how to get to the id itself.

One other way to get the user:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM