如何在身份验证失败时将 Symfony 4 中的 http_basic 防火墙配置为响应正文中的 return JSON?

How to configure http_basic firewall in Symfony 4 to return JSON in response body on authentication failure?

默认情况下,当您在 Symfony 中配置 http_basic 防火墙时,防火墙将 return“401 未授权”和带有无效凭据的请求的空主体。

我想要 return 定制 JSON(例如:{'errorCode' => 'AUTHORIZATION_FAILURE', 'errorMessage' => 'The provided credentials are not valid'})。这可能吗?

我的 onAuthenticationFailure 方法没有 return 我的自定义响应。它 return 是默认响应。

我的 AuthenticationListener class 将订阅这些事件:

<?php
namespace App\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class AuthenticationListener
{   
    public function onAuthenticationFailure(AuthenticationFailureEvent $event)
    {
        //executes on failed login
        $content = array('errorCode' => 'AUTHORIZATION_FAILURE', 'errorMessage' => 'The provided credentials are not valid');
        // dd(json_encode($content));

        //the bellow code is not working
        $response = new Response();
        $response->headers->set('Content-Type', 'application/json');
        $response->setContent(json_encode($content))
                ->setStatusCode(200);

        return $response;
    }
}
?>

我的安全 YAML

firewalls:
        api:
            pattern: ^/1
            anonymous: false
            provider: in_api
            http_basic: ~

我的服务 YAML

# authentication failure event listener
    acme.security.authentication_failure_event_listener:
        class: App\EventListener\AuthenticationListener
        arguments: [ api ]
        tags:
            - { name: kernel.event_listener, priority: 100, event: security.authentication.failure, method: onAuthenticationFailure }

当我使用 header('Content-Type: application/json');echo json_encode($content);exit; 时,它 returns 预期的结果。