如何在Symfony中配置http_basic防火墙以在响应正文中返回JSON?

Raz*_*van 6 basic-authentication symfony

默认情况下,当您http_basic在Symfony中配置防火墙时,防火墙将返回" 401 Unauthorized",并为失败的请求返回一个空主体.

我想让它返回一个自定义JSON(例如:) {success: false, error: 401}.这可能吗?

这是我的配置:

security:
    firewalls:
        api:
            http_basic:
                provider: myprovider
Run Code Online (Sandbox Code Playgroud)

aer*_*tal 5

您需要使用自定义AuthenticationEntryPoint。创建一个实现以下内容的类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;
    }    
}
Run Code Online (Sandbox Code Playgroud)

该类需要作为服务进行访问,因此请将其添加到中services.yml。将领域作为参数传递。

custom_basic_authentication_entry_point:
         class: AppBundle\CustomBasicAuthenticationEntryPoint
         arguments: [ main ]
Run Code Online (Sandbox Code Playgroud)

然后,您可以在中使用它security.yml

firewalls:
       main:
            anonymous: ~
            http_basic: ~
            entry_point: custom_basic_authentication_entry_point
Run Code Online (Sandbox Code Playgroud)