【问题标题】:How to configure http_basic firewall in Symfony 4 to return JSON in response body on authentication failure?如何在 Symfony 4 中配置 http_basic 防火墙以在身份验证失败时在响应正文中返回 JSON?
【发布时间】:2020-05-12 21:36:28
【问题描述】:

默认情况下,当您在 Symfony 中配置 http_basic 防火墙时,防火墙将返回“401 Unauthorized”,并且对于凭据无效的请求返回空正文。

我想让它返回一个自定义 JSON(例如:{'errorCode' => 'AUTHORIZATION_FAILURE', 'errorMessage' => 'The provided credentials are not valid'})。这可能吗?

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

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

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

【问题讨论】:

    标签: security symfony4 basic-authentication event-listener


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-10-13
      • 1970-01-01
      • 2013-07-04
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      相关资源
      最近更新 更多