You need to define an entry_point to your firewall in order for you to return unauthorized response. Information about entry points can be found in the documentation here. I will copy the paragraph in case of future requests here.
When the user is not authenticated at all (i.e. when the token storage has no token yet), the firewall's entry point will be called to "start" the authentication process. An entry point should implement AuthenticationEntryPointInterface, which has only one method: start(). This method receives the current Request object and the exception by which the exception listener was triggered. The method should return a Response object. This could be, for instance, the page containing the login form or, in the case of Basic HTTP authentication, a response with a WWW-Authenticate header, which will prompt the user to supply their username and password.
So in order for you to do that, you have to create a class that is going to 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
And finally pass the service id service.entry_point to your entry_point option in firewall section of security.yml file.
This should do the trick.