具有 LexikJWTAuthenticationBundle 和自定义登录响应的 Api 平台

问题描述 投票:0回答:1

我使用 symfony 7 和 api 平台以及 LexikJWTAuthenticationBundle

我有 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);
    }
}

它工作正常,但在示例响应中我仍然只看到“令牌”

我想调整示例响应。我创建了 DTO 类 LoginResponse 但如何在 openapi swagger 登录方法中使用它?

有什么想法吗?

php symfony api-platform.com lexikjwtauthbundle
1个回答
0
投票

services.json
中进行设置而不是使用注释时,它对我有用。来自官方文档

# 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 }

您可能需要专门设置您的

SerializerInterface
参数,像这里(我下面的代码未经测试):

# 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 }
© www.soinside.com 2019 - 2024. All rights reserved.