Symfony,如何在没有任何提供者的情况下创建防火墙验证器


Symfony, how tu create a firewall authenticator without any provider

我只想有一个过滤请求的服务(我没有令牌,也没有用户,也没有数据库等)

例如,如果它包含值为"yyyy"的标头"xxxxx",则请求将继续发送到控制器,如果没有,则应返回401响应。

我可以使用该服务创建一个监听器,并将其订阅到"kernel.controller"事件并验证最后提到的规则。

但我想知道我是否可以用安全捆绑包做到这一点,它只允许我将其应用于所需的URL等。

只需将SecurityListenerFactory添加到securityContainer:

/**
 * Class AppBundle
 *
 * @package AppBundle
 */
class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container); 
        $extension = $container->getExtension('security');
        $extension->addSecurityListenerFactory(new MySecurityFactory());
    }
}

创建自定义安全工厂:

/**
 * Class MySecurityFactory
 *
 * @package AppBundle'DependencyInjection'Security'Factory
 */
class MySecurityFactory implements SecurityFactoryInterface
{
    /**
     * @param ContainerBuilder $container
     * @param string           $id
     * @param array            $config
     * @param string           $userProvider
     * @param string           $defaultEntryPoint
     *
     * @return array
     */
    public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
    {
        $listenerId = 'security.listener.'.$id;
        $listener = $container->setDefinition($listenerId, new DefinitionDecorator('security.listener.'));
        return array($providerId, $listenerId, $defaultEntryPoint);
    }
    /**
     * @return string
     */
    public function getPosition()
    {
        return 'pre_auth';
    }
    /**
     * @return string
     */
    public function getKey()
    {
        return 'my_secret';
    }
    /**
     * @param NodeDefinition $node
     */
    public function addConfiguration(NodeDefinition $node)
    {
    }
}

并创建一个自定义侦听器:

/**
 * Class MySecurityListener
 *
 * @package AppBundle'Security'Firewall
 */
class MySecurityListener
{
    /**
     * @param GetResponseEvent $event
     */
    public function handle(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        try {
            // do things you like
        } catch (AuthenticationException $failed) {
            // ... you might log something here
        }
        // By default deny authorization
        $response = new Response();
        $response->setStatusCode(Response::HTTP_FORBIDDEN);
        $event->setResponse($response);
    }
}

但我建议使用例如preAuthToken或类似的。

希望能有所帮助。