You can override the default 401 JSON response for failed authentication by listening to the lexik_jwt_authentication.on_authentication_failure event and setting a custom JWTAuthenticationFailureResponse.
# config/services.yaml
services:
acme_api.event.authentication_failure_listener:
class: App\EventListener\AuthenticationFailureListener
tags:
- { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_failure, method: onAuthenticationFailureResponse }
// src/App/EventListener/AuthenticationFailureListener.php
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Response\JWTAuthenticationFailureResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
class AuthenticationFailureListener
{
public function onAuthenticationFailureResponse(AuthenticationFailureEvent $event)
{
$data = [
'name' => 'John Doe',
'foo' => 'bar',
];
$response = new JWTAuthenticationFailureResponse('Bad credentials, please verify that your username/password are correctly set', JsonResponse::HTTP_UNAUTHORIZED);
$response->setData($data);
$event->setResponse($response);
}
}