fefe
fefe

Reputation: 9055

LexikJWT get user profile by token

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.

Upvotes: 3

Views: 11083

Answers (2)

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.

Upvotes: 0

LBA
LBA

Reputation: 4109

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

Upvotes: 15

Related Questions