【问题标题】:Symfony2 Logout Event Listener IssueSymfony2 注销事件监听器问题
【发布时间】:2016-11-30 06:57:35
【问题描述】:

我正在向 Symfony2 项目添加审计日志,该项目将所有页面加载和发布请求记录到自定义审计表中。该项目使用 Symfony2 的默认注销路由(访问 /logout),它会破坏会话然后重定向到 /login 路由。

为 onKernelRequest 设置了一个事件侦听器,然后将正确的数据写入表中。在 security.yml 文件中,我为注销路线列出了以下内容。

security:
    firewalls:
        main:
            logout:
                path: /logout
                target: /login

审核日志记录在除注销事件之外的所有页面上都可以正常工作。注销后,我尝试访问分析器,然后从侧边栏中的“最后 10 个”选项中选择“/注销”操作。单击“事件”时,会列出 kernel.request 的默认 Symfony 事件,例如 DebugHandler 和 ProfileListener,但是我的自定义回调显示在“未调用的侦听器”选项卡下。

有一个 success_handler 可以添加到 security.yml 文件中,但是我需要一个可以在会话被销毁之前运行我的事件侦听器的方法。有没有办法让现有的监听器在 Symfony 执行注销之前也记录注销事件?

编辑

<?php

// src/AuditBundle/EventListener/AuditListener.php
namespace AuditBundle\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RequestStack;
use AuditBundle\Entity\AuditLog;

class AuditListener
{
    protected $requestStack;
    protected $em;
    protected $tokenStorage;
    protected $authorizationChecker;

    public function __construct(RequestStack $requestStack, \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage $tokenStorage, $authorizationChecker, \Doctrine\ORM\EntityManager $em = NULL)
    {
        $this->requestStack = $requestStack;
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
        $this->authorizationChecker = $authorizationChecker;
    }

    public function onKernelRequest(GetResponseEvent $response)
    {
        $request = $response->getRequest();
        if ( strpos($request->getRequestUri(), 'fonts') !== false)
            return;
        if ( strpos($request->getRequestUri(), 'css') !== false)
            return;
        if ( strpos($request->getRequestUri(), '_wdt') !== false)
            return;
        if ( strpos($request->getRequestUri(), 'js') !== false)
            return;

        if ( strpos($request->getRequestUri(), '_profiler') !== false)
            return;

        $this->log('Request', $request);
    }

    public function postUpdate(\Doctrine\ORM\Event\LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $this->em = $args->getEntityManager();
        $className = $this->em->getClassMetadata(get_class($entity))->getName();
        if ($entity instanceof \AuditBundle\Entity\AuditLog)
            return;
        $this->log($className.' Updated', $this->requestStack->getCurrentRequest(), $entity);
    }

    public function postPersist(\Doctrine\ORM\Event\LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $this->em = $args->getEntityManager();
        $className = $this->em->getClassMetadata(get_class($entity))->getName();
        if ($entity instanceof \AuditBundle\Entity\AuditLog)
            return;
        $this->log($className.' Created', $this->requestStack->getCurrentRequest(), $entity);
    }

    public function postDelete(\Doctrine\ORM\Event\LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $this->em = $args->getEntityManager();
        $className = $this->em->getClassMetadata(get_class($entity))->getName();
        if ($entity instanceof \AuditBundle\Entity\AuditLog)
            return;
        $this->log($className.' Deleted', $this->requestStack->getCurrentRequest());
    }

    protected function log($message, $request, $entity = NULL)
    {
        $log = new AuditLog();
        $log->setType($request->getRealMethod());
        if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY'))
        {
            $log->setUser($this->tokenStorage->getToken()->getUser());
        }
        if ($entity)
        {
            $log->setEntityId($entity->getId());
        }

        $log->setUriString($request->getRequestUri());
        $log->setMessage($message);
        $log->setDatetime(new \DateTime());
        $log->setIp($request->getClientIp());
        $log->setBrowser(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
        $this->em->persist($log);
        $this->em->flush();
    }
}

services.yml

services:
    audits.audit_listener:
        class: AuditBundle\EventListener\AuditListener
        arguments: [@request_stack, @security.token_storage, @security.authorization_checker, @doctrine.orm.entity_manager]
        tags:
            - { name: kernel.event_listener, event: kernel.request }

【问题讨论】:

  • 您能提供您的自定义回调类及其服务吗?
  • 您需要实现 LogoutHandlerInterface,并告诉配置您有一个注销处理程序,请参阅下面的答案

标签: php session symfony-2.8


【解决方案1】:

挂钩到 Symfony 的注销事件的最佳方法是像这样实现 LogoutHandlerInterface

事件监听器:

<?php

namespace AppBundle\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;

class MyListener implements LogoutHandlerInterface 
{
    public function logout(Request $request, Response $response, TokenInterface $token)
    {
        // Your handling here
    }   
}

配置:

services:
    appbundle_mylistener:
        class: AppBundle\EventListener\MyListener

security:
    firewalls:
        main:
            logout:
                handlers: [appbundle_mylistener]

所以您真正需要做的就是使用logout 方法从您的AuditListener 实现LogoutHandlerInterface,然后在配置中注册handlers 参数

【讨论】:

  • 这种方法适用于 Symfony v4.4。谢谢!
【解决方案2】:

由于我不清楚您的Audit logging 服务,我猜,注销事件是事先发生的。因此,您应该尝试通过实现另一个实现LogoutHandlerInterface 并依赖于您的Audit logging 服务的LogoutHandler 服务来调用您的Audit logging 服务。

我们在看到日志记录发生了什么之后就可以清楚地了解了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2016-08-26
    • 1970-01-01
    • 2015-04-07
    • 2012-02-01
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多