How to configure http_basic firewall in symfony to return JSON in response body?

By default, when you configure the firewall http_basicin Symfony, the firewall will return a " 401 Unauthorized" and an empty body for failed requests.

I would like it to return custom JSON (for example:) {success: false, error: 401}. Is it possible?

Here is my configuration:

security:
    firewalls:
        api:
            http_basic:
                provider: myprovider
+4
source share
1 answer

You need to use custom AuthenticationEntryPoint. Create a class that implements AuthenticationEntryPointInterface:

<?php

namespace AppBundle;

use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class CustomBasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface {

    private $realmName;

    public function __construct($realmName) {
        $this->realmName = $realmName;
    }

    public function start(Request $request, AuthenticationException $authException = null) {
        $content = array('success' => false, 'error' => 401);

        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
        $response->headers->set('Content-Type', 'application/json');
        $response->setContent(json_encode($content))
                ->setStatusCode(401);
        return $response;
    }    
}

The class must be available as a service, so add it to services.yml. Pass the kingdom as an argument.

custom_basic_authentication_entry_point:
         class: AppBundle\CustomBasicAuthenticationEntryPoint
         arguments: [ main ]

Then you can use it in security.yml:

firewalls:
       main:
            anonymous: ~
            http_basic: ~
            entry_point: custom_basic_authentication_entry_point
+2
source

Source: https://habr.com/ru/post/1599326/


All Articles