Api platform with LexikJWTAuthenticationBundle and Custom Login Response

97 views Asked by At

Im usage symfony 7 and api platform with LexikJWTAuthenticationBundle

I have onAuthenticationSuccessResponse

<?php

namespace App\EventListener;

use App\DTO\User\LoginResponse;
use App\Entity\User;
use App\Exception\InvalidUserStatusException;
use App\Util\ApiMessageUtil;
use App\Util\UserValidator;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\SerializerInterface;

#[AsEventListener(event: 'lexik_jwt_authentication.on_authentication_success', method: 'onAuthenticationSuccessResponse')]
readonly class AuthenticationSuccessListener
{
    public function __construct(private SerializerInterface $serializer)
    {
    }

    public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
    {
        $data = $event->getData();
        /** @var User $user */
        $user = $event->getUser();

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

        try {
            UserValidator::validateIfUserIsInactive($user);
        } catch (InvalidUserStatusException $exception) {
            throw new HttpException(Response::HTTP_UNAUTHORIZED);
        }

        $data['user'] = json_decode($this->serializer->serialize($user, 'json', ['groups' => 'login']), true);
        $event->setData($data);
    }
}

Its work fine but in example response i still see only "token"

I want to adjust example response. I create DTO class LoginResponse but how to use it in openapi swagger login method ?

enter image description here

Any ideas?

1

There are 1 answers

0
Skacc On

It worked for me when doing the setup in services.json rather then with annotations. From the official docs:

# config/services.yaml
services:
    acme_api.event.authentication_success_listener:
        class: App\EventListener\AuthenticationSuccessListener
        tags:
            - { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_success, method: onAuthenticationSuccessResponse }

You may need to specifically set up your SerializerInterface argument, like here (my code below was not tested):

# config/services.yaml
services:
    acme_api.event.authentication_success_listener:
        class: App\EventListener\AuthenticationSuccessListener
        arguments: [ '@serializer_interface' ]
        tags:
            - { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_success, method: onAuthenticationSuccessResponse }