2

Using LexikJWTAuthenticationBundle, FOSRest, FOSUser how do I get authenticated user profile by token. Is it possible?

So let's say user is already authenticated via LexikJWT and I have an api endpoint like /api/profile where I send the token and I expect to get specified user data.

I'm using for frontend ReactJS with Redux.

fefe
  • 8,755
  • 27
  • 104
  • 180
  • not sure if understand your question - when your token is an instance of TokenInterface what does $token->getUser() provide? – LBA Feb 13 '17 at 09:55

2 Answers2

12

This is an example of how to get your user by a service when the user is already authenticated:

class UserService
{

    /** @var  TokenStorageInterface */
    private $tokenStorage;

    /**
     * @param TokenStorageInterface  $storage
     */
    public function __construct(
        TokenStorageInterface $storage,
    )
    {
        $this->tokenStorage = $storage;
    }

    public function getCurrentUser()
    {
        $token = $this->tokenStorage->getToken();
        if ($token instanceof TokenInterface) {

            /** @var User $user */
            $user = $token->getUser();
            return $user;

        } else {
            return null;
        }
    }
}

And in your services.yml:

tenant_user_service:
    class: YourBundle\YourPackage\UserService
    arguments: [ '@security.token_storage' ]

This will return your user - but be aware depending on the how user got set to the token during authentication this can be as well only your username as a string. But basically you get any content from your current $token->getUser().

LBA
  • 3,859
  • 2
  • 21
  • 60
  • thanks for feedback! I'm still not able to understand your point. So the scenario would be: having protected route to `api/profile` user authenticate itself and via react routing making a request to profile route and as response should get back some user specific data, like avatar etc.. At this point how my Controller knows about user? – fefe Feb 18 '17 at 15:06
  • 1
    controller should know user by: `$this->getUser()` which is a shortcut in every Symfony's controller which is extended and used the 'standard way' – LBA Feb 20 '17 at 10:16
  • yes you are right, but I had my controller as service declared and I needed to inject `@security.token_storage` – fefe Feb 21 '17 at 18:40
0

i'm new but i can try...

you can use the annotation like

@Security("is_granted('ROLE_USER')")

in your controller and something like$this->getUser()->getUsername(); to get the username.

example:

$user = $this->get('doctrine.orm.default_entity_manager')
    ->getRepository('AppBundle:User')
    ->FindOne($this->getUser()->getUsername());`

after that you serialize datas, create new Response and return it.

Jason Roman
  • 8,146
  • 10
  • 35
  • 40