4

I am using Symfony 3.4 and LexikJWTAuthenticationBundle 2.4. Do you know how to retrieve the user that is accessing the API endpoint?

Normally, I would call $user = $this->get('security.token_storage')->getToken()->getUser(); but that doesn't seem to work in this case.

burki
  • 2,946
  • 6
  • 37
  • 51
  • You should be able to just type hint the current user in the controller `public function someAction(UserInterface $user)` if it doesn't work do you get any errors? If nothing helps I'd try going over the configuration steps for LexikJWT again – JimL Jan 07 '18 at 00:24

2 Answers2

3

Advice for you, use container key in controller.

Of course, it's better to send the your error here!

Symfony 4

protected function getCurrentUser()
    {

        if (!$this->container->has('security.token_storage')) {
            throw new \LogicException('The Security Bundle is not registered in your application.');
        }
        if (null === $token = $this->container->get('security.token_storage')->getToken()) {
            return;
        }
        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }
        return $user;
    }
ShahRokh
  • 1,005
  • 14
  • 31
-2

I was having the same issue, you can get Id of current user by using :

$current_user = $this->getUser();

$id = $current_user->getId();

Inside your controller.

mockingbid
  • 169
  • 12