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