вернуть пользовательский код состояния в User Checker - PullRequest
0 голосов
/ 11 апреля 2020

Я работаю с Symfony 4.4. Я использую аутентификацию JWT и сейчас создаю пользовательскую проверку пользователя: я хочу вернуть пользовательский код ответа и пользовательское сообщение, когда пользовательская проверка обнаруживает, что пользователь не может подключиться.

security.yaml:

    client_login:
        pattern:  ^/api/login
        provider: client_entity
        stateless: true
        anonymous: true
        json_login:
            check_path: api_login
            username_path: email
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
        user_checker: App\Security\UserChecker
    refresh:
        pattern:  ^/api/token/refresh
        stateless: true
        anonymous: true
    api:
        pattern:   ^/api
        stateless: true
        anonymous: true
        guard:
            authenticators:
                - App\Security\TokenAuthenticator
            provider: chain_providers #this provider will be ignored when getting the User
        user_checker: App\Security\UserChecker

UserChecker:

class UserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        return;
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user instanceof Client) {
            return;
        }

        if (!$user->isActive()) {
            throw new AuthenticationException('userNotActive');
        }
    }
}

С помощью этого средства проверки пользователя, когда клиент не активен:

{
"code": 401,
"message": "An authentication exception occurred."
}

Я хочу просто настроить код и сообщение.

1 Ответ

1 голос
/ 11 апреля 2020

Если вы хотите обновить только ответ, вы должны создать список для обработки аутентификации ошибок:

<?php

namespace App\EventListener;

use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;

/**
 * Authentication Failure Listener.
 *
 * This listener add data to payload.
 */
class AuthenticationFailureListener
{
    /**
     * When this event happened, response can be updated.
     *
     * @param AuthenticationFailureEvent $event the authentication Failure event
     */
    public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event): void
    {
        $response = $event->getResponse();

        //TODO : edit your response here
        //dd($response);

        $event->setResponse($response);
    }
}

Объявите службу в файле services.yaml:

    App\EventListener\AuthenticationFailureListener:
        tags:
            - { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_failure, method: onAuthenticationFailureResponse }
...