Adding public data to the JWT response with lexik

Viewed 2265

I am currently using Symfony 5 with lexik and when I to generate the JWT token, I would like for the response to get me the token and the username so I could have something like this:

{
    "username":"username"
    "token": "token"
}

I tried of course to use the doc here : https://github.com/lexik/LexikJWTAuthenticationBundle/blob/master/Resources/doc/2-data-customization.md#eventsauthentication_success---adding-public-data-to-the-jwt-response but whenever I test it in Postman, I still only get the token and I am completely stuck on what to do...

My EventListener:

<?php

namespace App\EventListener;

use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;


class AuthenticationSuccessListener
{
    /**
     * @param AuthenticationSuccessEvent $event
     */
    public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event)
    {
        $data = $event->getData();
        $user = $event->getUser();

        if (!$user instanceof UserInterface) {
            return;
        }

        $data['data'] = array(
            'username' => $user->getUsername(),
        );

        $event->setData($data);
    }
}

the service in services.yaml

acme_api.event.authentication_success_listener:
        class: App\EventListener\AuthenticationSuccessListener
        tags:
            - { name: kernel.event_listener, event: lexik_jwt_authentication.handler.authentication_success, method: onAuthenticationSuccessResponse }

Any help would be greatly appreciated

1 Answers

Try to add the user interface use inside your Listener it might be that you are not getting throw your if statment because of this:

use Symfony\Component\Security\Core\User\UserInterface;
Related