【问题标题】:How to configure http_basic firewall in Symfony to return JSON in response body?如何在 Symfony 中配置 http_basic 防火墙以在响应正文中返回 JSON?
【发布时间】:2015-10-13 21:22:53
【问题描述】:

默认情况下,当您在 Symfony 中配置 http_basic 防火墙时,防火墙将返回“401 Unauthorized”,并为失败的请求返回一个空正文。

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

这是我的配置:

security:
    firewalls:
        api:
            http_basic:
                provider: myprovider

【问题讨论】:

    标签: symfony basic-authentication


    【解决方案1】:

    您需要使用自定义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;
        }    
    }
    

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

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

    然后你就可以在security.yml中使用它了:

    firewalls:
           main:
                anonymous: ~
                http_basic: ~
                entry_point: custom_basic_authentication_entry_point
    

    【讨论】:

    • 看起来这是对原始问题的正确答案。你应得的赏金。可悲的是,它没有回答我自己的问题:向 http_basic 添加 AuthenticationSuccess 处理程序或侦听器。
    • 我终于通过AuthenticationEvents::AUTHENTICATION_SUCCESS 的自定义侦听器实现了我的目标,并检查$event-&gt;getAuthenticationToken()-&gt;getRoles() 以查看用户是否经过身份验证(而不是匿名令牌)。
    • @Alsciende 从SecurityBundle 参考配置(symfony.com/fr/doc/current/reference/configuration/…)来看,http_basic 似乎没有处理程序。
    猜你喜欢
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多