9

我的问题是捕获用户注销。我拥有的代码是:

public  function onAuthenticationFailure(Request $request, AuthenticationException $exception){

    return new Response($this->translator->trans($exception->getMessage()));
}

public function logout(Request $request, Response $response, TokenInterface $token)
{
    $empleado = $token->getUser();
    $log = new Log();
    $log->setFechalog(new \DateTime('now'));
    $log->setTipo("Out");
    $log->setEntidad("");
    $log->setEmpleado($empleado);
    $this->em->persist($log);
    $this->em->flush();
}

public function onLogoutSuccess(Request $request) {
    return new RedirectResponse($this->router->generate('login'));
}

TokenInterface问题是当您运行注销功能时我无法访问用户令牌?

4

3 回答 3

14

要获取令牌,您必须注入安全上下文。

1. 创建类 Logout 监听器,如下所示:

namespace Yourproject\Yourbundle\Services;
...
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;

class LogoutListener implements LogoutSuccessHandlerInterface {

  private $security;  

  public function __construct(SecurityContext $security) {
    $this->security = $security;
  }

  public function onLogoutSuccess(Request $request) {
     $user = $this->security->getToken()->getUser();

     //add code to handle $user here
     //...

     $response =  RedirectResponse($this->router->generate('login'));

    return $response;
  }
}

2. 然后在 service.yml 中,添加这一行:

....
logout_listener:
   class:  Yourproject\Yourbundle\Services\LogoutListener
   arguments:  [@security.context]

就是这样,希望有帮助。

于 2012-11-09T05:24:23.643 回答
8

请参阅http://symfony.com/doc/current/reference/configuration/security.html

安全.yml

secured_area:

    logout:
        path:   /logout
        **success_handler: logout_listener** 
于 2014-07-24T15:22:04.753 回答
0

看看这里是否可以覆盖捆绑包的任何控制器:

http://symfony.com/doc/current/cookbook/bundles/inheritance.html

于 2014-11-19T05:12:20.957 回答