protected function registerAuthenticationFactory(\Silex\Application $app,
                                                     $id,
                                                     AuthenticationFactoryInterface $authFactory,
                                                     UserProviderInterface $userProvider)
    {
        $fac = 'security.authentication_listener.factory.'.$id;
        if (isset($app[$fac])) {
            return;
        }

        $app[$fac] = $app->protect(function ($name, $options) use ($app, $id, $authFactory, $userProvider) {
            // the authentication type
            $type        = (isset($options['login_path']) ? 'form' : 'http');
            $entry_point = "security.entry_point.$name.$type";
            if ($type == 'form') {
                $options['failure_forward'] = true;
            }

            // the authentication provider id
            $auth_provider       = "security.authentication_provider.$name.$id";
            $app[$auth_provider] = $app->share(function () use ($app, $name, $authFactory, $userProvider) {
                return $authFactory->createAuthenticationProvider($app, $userProvider, $name);
            });

            // the authentication listener id
            $auth_listener = "security.authentication_listener.$name.$type";
            if (!isset($app[$auth_listener])) {
                $app[$auth_listener] = $app["security.authentication_listener.$type._proto"]($name, $options);
            }

            return array($auth_provider, $auth_listener, $entry_point, 'pre_auth');
        });
    }