i would like to do something like that in controller to log user out:
$user = $this->get('security.context')->getToken()->getUser(); $user->logOut();
Logout in Symfony2 is handled by so called logout handler which is just a lister that is executed when URL match pattern from security configuration, ie. if URL is let's say /logout
then this listener is executed. There are two build-in logout handlers:
All you have to do is the very same the last one does. You can achieve it by simply calling:
$this->get('security.context')->setToken(null); $this->get('request')->getSession()->invalidate();
$this->get('security.token_storage')->setToken(null); $this->get('request')->getSession()->invalidate();
This will only work when remember me functionality is disabled. In other case, user will be logged in back again by means of a remember me cookie with the next request.
Please consider the extended solution if you are using remember me functionality: https://stackoverflow.com/a/28828377/1056679
Invalidating the user's session might cause some unwanted results. Symfony's firewall has a listener that always checks and refreshes the user's token. You could just do a redirect to the default logout route that you have specified in your firewall.yml
(or security.yaml
)
In Controller you can do this:
$this->redirect($this->generateUrl('your_logout_url'));
If you don't know the name of the logout route (your_logout_url
), you can get it from the Symfony console by using this command:
app/console router:match /logout
Or newer Symfony versions:
bin/console router:match /logout
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With