会话应在symfony2中10分钟后注销

时间:2015-05-15 10:38:57

标签: symfony listener

到目前为止我试过了,

Path CoreBundle / DependencyInjection / configuration.php

namespace Funstaff\CoreBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class FunstaffCoreExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container,
                         new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $container->setParameter('core.timeout', $config['timeout']);
    }
}

我们将在FunstaffCoreExtension.php文件中添加此代码

funstaff_core:
    timeout:    600 

在config.yml中。

namespace Funstaff\CoreBundle\Request\Listener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class RequestListener implements EventSubscriberInterface
{
    protected $session;

    protected $securityContext;

    protected $timeout;

    /**
     * Construct
     * 
     * @param Session $session
     */
    public function __construct(Session $session,
                                SecurityContext $securityContext,
                                $timeout)
    {
        $this->session = $session;
        $this->securityContext = $securityContext;
        $this->timeout = $timeout;
    }

    /**
     * Get Subscribed Events
     * 
     * @return array event list
     */
    public static function getSubscribedEvents()
    {
        return array(
            'kernel.request' => 'onKernelRequest',
        );
    }

    /**
     * On Kernel Request
     */
    public function onKernelRequest(GetResponseEvent $event)
    {

        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }

        $meta = $this->session->getMetadataBag();
        $lastused = $meta->getLastUsed();

        if (null !== $lastused && (time() - $lastused) > $this->timeout) {
            $this->securityContext->setToken(null);
            $this->session->invalidate();
        }
    }
}

我在以下路径中创建了RequestListener.php文件:FunstaffCoreBundle / Request / Listener。

services:
    timeout.request.listener:
        class: Funstaff\CoreBundle\Request\Listener\RequestListener
        arguments: [ @session, @security.context, %funstaff.timeout% ]
        tags: 
            - { name: kernel.event_subscriber }    

&安培;在Resources / config / services.yml

<bindings>
    <binding protocol="http" bindingInformation="*:1234:company-localdev.com" />
</bindings>

但它没有工作会话超时。 什么离开了我? 请有人知道,然后告诉我。

1 个答案:

答案 0 :(得分:3)

我找到了解决方案。

创建文件夹处理程序&amp;在处理程序中创建文件.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace my\DemoBundle\Handler;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContextInterface;

/**
 * Description of SessionIdleHandler
 *
 */
class SessionIdleHandler {
    protected $session;
    protected $securityContext;
    protected $router;
    protected $maxIdleTime;


    public function __construct(SessionInterface $session, SecurityContextInterface $securityContext, RouterInterface $router, $maxIdleTime = 0)
    {
        $this->session = $session;
        $this->securityContext = $securityContext;
        $this->router = $router;
        $this->maxIdleTime = $maxIdleTime;        
    }

    public function onKernelRequest(GetResponseEvent $event)
    {                
        if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {

            return;
        }

        if ($this->maxIdleTime > 0) {

            $this->session->start();
            $lapse = time() - $this->session->getMetadataBag()->getLastUsed();

            if ($lapse > $this->maxIdleTime) {

                $this->securityContext->setToken(null);
                $this->session->getFlashBag()->set('info', 'You have been logged out due to inactivity.');

                //Redirect URL to logout               
                $event->setResponse(new RedirectResponse($this->router->generate('logout')));
            }
        }
    }
}

在service.yml文件中

services:
    my.handler.session_idle:
           class: my\DemoBundle\Handler\SessionIdleHandler
           arguments: ["@session", "@security.context", "@router", %session_max_idle_time%]
           tags:
               - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

在parameter.yml

中设置参数(以秒为单位)
session_max_idle_time: 600

它完美无缺。