Symfony2 - 更改安全入口点

时间:2015-08-10 09:10:18

标签: rest symfony http-headers

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

 WWW-Authenticate : Basic realm=XXX

但是类似

WWW-Authenticate : myOwnBasic realm=XXX

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

1 个答案:

答案 0 :(得分:1)

我终于找到了解决方案:

您需要在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;
    }
}