You need to define an entry_point for your firewall so that you can return an unauthorized response. Information on entry points can be found in the documentation here . I will copy this paragraph in case of future requests here.
When the user is not authenticated at all (that is, when the token store does not yet have a token), the firewall entry point will be called to βstartβ the authentication process. The entry point must implement AuthenticationEntryPointInterface, which has only one method: start (). This method receives the current Request object and the exception from which the exception listener was called. The method should return a Response object. This could be, for example, a page containing a login form or, in the case of basic HTTP authentication, a response with a WWW-Authenticate heading that will prompt the user to provide their username and password.
So, to do this, you need to create a class that will be defined as a service.
It should look like this:
namespace MyBundle\Service; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; class CustomEntryPoint implements AuthenticationEntryPointInterface { public function start(Request $request, AuthenticationException $authException = null) { $response = new Response("", Response::HTTP_UNAUTHORIZED); return $response; } }
And in your services.yml file
services: service.entry_point: class: MyBundle\Service\CustomEntryPoint
Finally, pass the service.entry_point service identifier to entry_point in the firewall section of the security.yml file.
That should do the trick.
source share