【发布时间】: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