Reputation: 37
I have a difficulty, and I've been wandering around the internet for a while looking for the solution.
I'm using API Platform with JWT authentication, following the steps in https://api-platform.com/docs/core/jwt/ and it works really well. But I need to know if I can return the user data in the response, along with the Token, because I need to use it in the frontend. I really can't find how to do it, neither in the official documentation, nor by analyzing the bundle itself.
Is there any way?
Upvotes: 1
Views: 1570
Reputation: 26
Not sure if this is best practice, but you could create a custom Event Listener, one that uses the Lexik Authentication Success. That returns the token information
<?php
namespace App\EventListener;
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
class LoginSuccessListener
{
public function onLoginSuccess(AuthenticationSuccessEvent $event): void
{
$user = $event->getUser();
$payload = $event->getData();
if (!$user instanceof User) {
return;
}
// Add information to user payload
$payload['user'] = [
...
];
$event->setData($payload);
}
}
And then in your services.yaml, you'll need to register the Listener
#services.yaml
App\EventListener\LoginSuccessListener:
tags:
- { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_success, method: onLoginSuccess }
Upvotes: 1