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

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'));
}

问题是在运行注销功能时我无法访问用户 token TokenInterface

最佳答案

要获得 token ,必须注入(inject)安全上下文。

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]

就是这样,可能会有所帮助。

关于php - symfony2注销,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12743213/

10-13 09:04