Symfony 2.6.6 security - How to logout or reset TokenStorage with user provider using in_memory?
I was struggling a bit with the recently myself. What I got to work was:
- Create a route for /logout & pass it to a the Default Controller logoutAction() function
- Add logoutAction() function to DefaultController.php that sets token to NULL and redirects you to root
#/app/config/routing.yml#...logout: path: /logout defaults: { _controller: AppBundle:Default:logout }
#/src/AppBundle/Controller/DefaultController.phpuse Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;use Symfony\Component\HttpFoundation\RedirectResponse;class DefaultController extends Controller{ public function logoutAction() { $this->get('security.token_storage')->setToken(NULL); // Redirect User to Root/Hello/Wherever return new RedirectResponse($this->generateUrl('hello')); } //...}
Note the additional "use" lines in DefaultController.php
In Symfony, you can add your own success handler to logout route. So you can do something like below. This is a simple notation, using the logout path set in parameters.yml. In more elaborate example you can fetch the security component configuration and get the logout path from there, but this is much more complex.
This solution's advantage is that it plugs directly into security component flow - all other actions needed on log out are executed correctly.
parameters.yml
parameters: (...) %logout_target%: / (...)
security.yml
security: default: anonymous: ~ http_basic: ~ logout: path: /logout target: / success_handler: your.success.handler.service
services.yml
parameters: logout_target: /services: your.success.handler.service: class: \Your\SuccessHandlerClass arguments: - @security.http_utils - @security.token_storage - %logout_target%
src/Your/SuccessHandlerClass.php
<?phpnamespace Your;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;use Symfony\Component\Security\Http\HttpUtils;use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;class SuccessHandlerClass extends DefaultLogoutSuccessHandler{ /** * * @var TokenStorageInterface */ private $tokenStorage; public function __construct(HttpUtils $httpUtils, TokenStorageInterface $tokenStorage, $targetUrl = '/') { parent::__construct($httpUtils, $targetUrl); $this->tokenStorage = $tokenStorage; } public function onLogoutSuccess(Request $request) { $this->tokenStorage->setToken(null); return parent::onLogoutSuccess($request); }}