Symfony, force logout in a controller
Asked Answered
F

2

5

I'm using Symfony 3.4, and I would like to logout my user at the end of my action in my controller.

This is the action

public function changeUserEmail() {
     /* change the user email */
     /* perform the logout */
     /* choose the route to redirect to */
     return $this->redirectToRoute(/* some route choosen above */);
}

Is there a way to implement /* perform the logout */ the Symfony way? I found nothing in the docs. I do want to logout in the controller (don't want to redirect to the logout path) and I want to choose the route to be redirected in the controller.

Many thanks.

Version or Symfony is 3.4

Flitter answered 26/10, 2018 at 9:43 Comment(2)
Possible duplicate of How can one force logout a user in Symfony?Armament
I think you can just set the security context token to null, then invalidate the session. More of a Laravel guy when using PHP, but in theory this should workBrainstorm
F
5

Here is the answer

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

// ...

public function changeUserEmail(TokenStorageInterface $tokenStorage) {
     /* change the user email */
     $tokenStorage->setToken();
     /* choose the route to redirect to */
     return $this->redirectToRoute(/* some route choosen above */);
}

There is no need to invalidate all the session, e.g. if one have multiple firewalls defined.

Flitter answered 26/10, 2018 at 11:8 Comment(4)
Working with Symfony 4 too.Matthia
Not sure this is something that should live in a controller. Some random controller setting the token storage to empty seems a bit out of place? Why not just redirect to the app's logout handler directly?Contretemps
@Contretemps because I can't trust the fact that the user will ever follow the redirect, and because I do want to choose the route inside the controller.Flitter
Yes, controller should decide the ultimate route to send to. However setting tokens belongs in auth or security layer, a new class that can be called on in various places to set (or empty) the user's token - or use the app's logout handler. If you have random issues/bugs with eg logout or whatever, raking your controllers to see where a user may have been logged out is tiresome.Contretemps
M
1

With symphony 6.2 you can use the logout() method:

use Symfony\Bundle\SecurityBundle\Security;

class SecurityController
{
    public function someAction(Security $security): Response
    {
        //  with csrf
        $response = $security->logout();

        // or without csrf
        $response = $security->logout(false);

        // ... return $response (if set) or e.g. redirect to the homepage
    }
}
Maltha answered 21/3, 2023 at 13:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.