【问题标题】:return a custom status code in User Checker在用户检查器中返回自定义状态码
【发布时间】:2020-04-11 11:06:42
【问题描述】:

我正在使用 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

用户检查器:

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."
}

我只想自定义代码和消息。

【问题讨论】:

    标签: symfony symfony-4.4


    【解决方案1】:

    如果你只想更新响应,你应该创建一个监听器来处理失败认证:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      相关资源
      最近更新 更多