Symfony2: how to log user out manually in controller?

后端 未结 5 621
清酒与你
清酒与你 2020-11-28 23:35

i would like to do something like that in controller to log user out:

$user = $this->get(\'security.context\')->getToken()->getUser();
$user->lo         


        
5条回答
  •  时光取名叫无心
    2020-11-29 00:05

    In case you are using symfony 4.x (I haven't tested other versions, so it still might work), you may want to use the internal logout handler of symfony (highly recommended, as it will take care of everything for you in a clean way, cookies and all). You don't need to write too much code for that either, you can simply emulate a logout request:

    ... // Some code, that leads you to force logout the user 
    // Emulating logout request
    $logoutPath = $this->container->get('router')->generate('app_logout');
    $logoutRequest = Request::create($logoutPath);
    $logoutResponse = $this->container->get('http_kernel')->handle($logoutRequest);
    // User is logged out now
    ... // Stuff to do after logging out, eg returning response
    

    This will make symfony do the request response flow, thus it will call the logout handler internally. This method allows you to proceed to further custom code. Otherwise, if you invoked only the logout listener here, you would have to return the usual logout response, that now is in $logoutResponse. Optionally, if you want to return it, you would also simply:

    return $logoutResponse;
    

提交回复
热议问题