Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: how to log user out manually in controller?

Tags:

symfony

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

$user = $this->get('security.context')->getToken()->getUser(); $user->logOut(); 
like image 548
VitalyP Avatar asked Jun 24 '11 07:06

VitalyP


2 Answers

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:

  1. CookieClearingLogoutHandler which simply clears all cookies.
  2. SessionLogoutHandler which invalidates the session

All you have to do is the very same the last one does. You can achieve it by simply calling:

Legacy Symfony

$this->get('security.context')->setToken(null); $this->get('request')->getSession()->invalidate(); 

Symfony 2.6

$this->get('security.token_storage')->setToken(null); $this->get('request')->getSession()->invalidate(); 

Warning

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

like image 68
Crozin Avatar answered Oct 13 '22 00:10

Crozin


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 

:)

like image 21
Francis Avatar answered Oct 12 '22 22:10

Francis