Symfony2 - 更改安全入口点

Symfony2 - change security entry point

使用 symonfy 作为 REST API,我希望服务器不要在 401 上发送这样的 headers :

 WWW-Authenticate : Basic realm=XXX

但是像

WWW-Authenticate : myOwnBasic realm=XXX

如何重载 BasicAuthenticationEntryPoint class 或为基本身份验证创建自己的入口点 class?

我终于找到了解决方案:

您需要在 parameters.yml 中覆盖此参数:

    security.authentication.basic_entry_point.class: NAMESAPCE\YOURCUSTOM_CLASS

然后在您喜欢的地方创建一个文件(我在 MyBundle\Security\Http\EntryPoint 中制作),看起来像:

<?php

namespace NAMESAPCE;

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

class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint
{
    private $realmName;

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

    /**
     * {@inheritdoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        $response = new Response();
        $response->headers->set('WWW-Authenticate', sprintf('myOwnBasic realm="%s"', $this->realmName));
        $response->setStatusCode(401);

        return $response;
    }
}