1

I'd like to create some service that would be responsible for auto-redirecting some routes to secure version of the URL. For example:

http://domain.com/checkout -> https://secure.domain.com/checkout
http://domain.com/about // route not marked as secure, no redirection

I know I can partially achieve that with schema:

secure:
    path:     /secure
    defaults: { _controller: AcmeDemoBundle:Main:secure }
    schemes:  [https]

However I also need to change hosts. Should I hook up to some kernel events or something?

4

2 回答 2

1

我最终得到的是:

1)我在路由(https)中设置了一个自定义选项:

acme_dynamic:
    pattern:  /
    options:
        https: true
    defaults:
        _controller: acmeCommonBundle:Default:dynamic

2)我为kernel.response事件创建了一个监听器:

namespace acme\CommonBundle\EventListener;

use acme\CommonBundle\Controller\HttpsController;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class HttpsControllerListener
{
    /**
     * Base HTTPS Url
     * @var string
     */
    private $httpsUrl;

    /**
     * Request
     * @var [type]
     */
    private $request;

    /**
     * [$router description]
     * @var [type]
     */
    private $router;

    public function __construct($httpsUrl, $request, $router)
    {
        $this->httpsUrl = $httpsUrl;
        $this->router = $router;
        $this->request = $request;
    }

    public function onKernelResponse(FilterResponseEvent $event)
    {
        $routeCollection = $this->router->getRouteCollection();
        $route = $routeCollection->get($this->request->get('_route'));

        if ($route and $route->getOption('https') === true and $this->request->server->get('HTTPS')) {
            $response = $event->getResponse();
            $event->setResponse(new RedirectResponse($this->httpsUrl . $this->request->server->get('REQUEST_URI')));
        }
    }
}

3)我已将其注册到上述事件:

acme.https_controller_listener:
    class: acme\CommonBundle\EventListener\HttpsControllerListener
    arguments: [%baseurl.https%, @request, @router]
    scope: request
    tags:
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

基本上它拦截响应,检查当前路由是否https在路由配置中设置了选项,如果有,检查它是否在安全连接上 - 如果没有,则重定向到安全域。

于 2013-09-09T12:47:59.510 回答
0

您可以在Symfony\Component\HttpKernel\KernelEvents::REQUEST事件中使用监听器,文档如何在此处创建类似的监听器:http: //symfony.com/doc/current/cookbook/service_container/event_listener.html。这样你就可以添加你需要的任何逻辑。您将GetResponseEvent作为参数获取,因此您可以从方法返回或设置对该事件的重定向响应。

于 2013-09-06T21:04:22.247 回答