默认情况下,当你在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 }
当我使用 header('Content-Type: application/json');echo json_encode($content);exit;
它返回预期的结果。